I want to pass arguments to a function that aren't to be evaluated until they're used within the function. As a trivial example, how would I go about if I wanted to pass ... = foo, 'bar'
to the following function, while foo
is defined within the function:
myfunc <- function(X, ...) {
for (foo in seq_along(X)) {
cat(..., '\n')
}
}
myfunc(X = 1:5, foo, 'bar')
I tried using cat(substitute(...), '\n')
, which seems to merely omit foo
.
Thanks!
1) Use eval(substitute(...))
myfunc <- function(X, ...) {
for (foo in seq_along(X)) {
eval(substitute(cat(..., "\n")))
}
}
myfunc(X = 1:5, foo, 'bar')
giving:
1 bar
2 bar
3 bar
4 bar
5 bar
2) defmacro Another approach is to create a macro using defmacro
in gtools:
library(gtools)
myfunc2 <- defmacro(X, DOTS, expr = {
for (foo in seq_along(X)) {
cat(..., "\n")
}
})
myfunc2(X = 1:5, foo, 'bar')