I have a function called foo()
. The arguments are ...
.
But I want loop over the individual arguments in ...
. For example, if user inputs col = c(2,3)
, I want the first round of lapply()
to use col = 2
and the second round of lapply()
to use col = 3
and so on.
Is this possible in R?
Reproducible R code:
foo <- function(...){
x <- list(...)
n_plots <- lengths(x)[1]
par(mfrow = n2mfrow(n_plots))
lapply(1:n_plots, \(i) plot(1:10, ...))
}
# EXAMPLE OF USE:
foo(col = 2:3, pch = c(19,21))
This is a little convoluted (uses ...
twice) but seems to do the trick, for an arbitrary number of arguments:
foo <- function(...){
L <- list(...)
n_plots <- lengths(L)[1]
par(mfrow = n2mfrow(n_plots))
ff <- function(...) {
args <- c(list(x = 1:10), list(...))
do.call(plot, args)
}
Map(ff, ...)
}
foo(col = 2:3, pch = c(19,21), cex = 2:3)