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?
In technical language, this is called an ellipsis. And it means that the function is designed to take any number of named or unnamed arguments. By the way, the ellipsis is not a specialty of R. Other programming languages have the same or a similar concept.
Functions are defined using the function() directive and are stored as R objects just like anything else. In particular, they are R objects of class “function”. Here's a simple function that takes no arguments and does nothing.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With