Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R functions: passing arguments with ellipsis

Tags:

r

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?

like image 300
user54101 Avatar asked Nov 24 '16 21:11

user54101


People also ask

What does three dots mean in R function?

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.

Can an R function have no arguments?

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.


1 Answers

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
like image 93
Scott Warchal Avatar answered Sep 22 '22 10:09

Scott Warchal