Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Avoiding code repetition with (box)plot functions

For generating a couple of boxplots with the same style, I make identical calls to the boxplot function like in the following minimal example:

boxplot(Petal.Length ~ Species, iris, ylim=c(0,10))
abline(h=8)
legend('topleft',levels(iris$Species))

boxplot(Sepal.Length ~ Species, iris, ylim=c(0,10))
abline(h=8)
legend('topleft',levels(iris$Species))

I would like keep my code readable and maintainable by avoiding code duplication.

Therefore, I thought of using decorators as described in
How customize a plot inside a R function which belong to a package? or
Writing a decorator for R functions or
https://weinstockjosh.com/post/2016-06-08-decorators-in-r/
However, I could not find a way to encapsulate/wrap around the formula used as a parameter in the (box)plot functions, which is beautiful syntactic sugar.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Where could I find a suitable construct offered by R to keep my code readable and maintainable?

>Solution :

Using lapply and reformulate

lapply(c('Petal.Length', 'Sepal.Length'), \(x) {
  boxplot(reformulate(x, 'Species'), iris, ylim=c(0, 10))
  abline(h=8)
  legend('topleft', levels(iris$Species))
})
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading