user54101 user54101 - 11 days ago 6
R Question

R functions: passing arguments with ellipsis

I have a question regarding base R usage. It might be asked before, however I wasn't able to find solution to my problem.

I have a function that calls another function. Arguments to second function are passed using ellipsis (

...
). However, I get error message:
object "OBJECT" not found
.

f1 <- function(a, ...) {
print(a)
f2(...)
}
f2 <- function(...) {
print(b == TRUE)
print(runif(c))
}
f1(2, b = FALSE, c = 2)


Which gives me:
Error in print(b == TRUE) : object 'b' not found
.

I know that it is possible to get around this problem using
args <- list(...)
and then calling each argument separately, but I imagine that this gets complicated when having lots of arguments (not only two).

Question

How to pass arguments from
f1
to
f2
using ellipsis?

Answer

So the ellipses are used to save you specifying all the arguments of f2 in the arguments of f1. Though when you declare f2, you still have to treat it like a normal function, so specify the arguments b and c.

f1 <- function(a, ...) {
    print(a)
    f2(...)
}

# Treat f2 as a stand-alone function
f2 <- function(b, c) {
    print(b == TRUE)
    print(runif(c))
}

f1(2, b=FALSE, c=2)

[1] 2
[1] FALSE
[1] 0.351295 0.9384728
Comments