Search code examples
rplotrefactoringdecorator

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.

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))
    })