R Yoda
R Yoda

Reputation: 8750

Call an R function with run-time generated ellipsis arguments (dot-dot-dot / three dots)

I want to call an R function that uses the ... (ellipsis) argument to support an undefined number of arguments:

f <- function(x, ...) {
  dot.args <- list(...)
  paste(names(dot.args), dot.args, sep = "=", collapse = ", ")
}

I can call this function passing the actual arguments predefined during design-time, e. g.:

> f(1, a = 1, b = 2)
[1] "a=1, b=2"

How can I pass actual arguments for ... that I know only at run-time (e. g. input from the user)?

# let's assume the user input was "a = 1" and "b = 2"
# ------
# If the user input was converted into a vector:
> f(1, c(a = 1, b = 2))
[1] "=c(1, 2)"                # wrong result!
# If the user input was converted into a list:
> f(1, list(a = 1, b = 2))
[1] "=list(a = 1, b = 2)"     # wrong result!

The expected output of the dynamically generated f call should be:

[1] "a=1, b=2"

I have found some existing questions on how to use ... but they did not answer my question:

How to use R's ellipsis feature when writing your own function?

Usage of Dot / Period in R Functions

Pass ... argument to another function

Can I remove an element in ... (dot-dot-dot) and pass it on?

Upvotes: 5

Views: 1375

Answers (1)

user2957945
user2957945

Reputation: 2413

You can do this by passing the function arguments using do.call. First force to list using as.list.

eg

input <- c(a = 1, b = 2)
do.call(f,  as.list(input))

input <- list(a = 1, b = 2)
do.call(f,  as.list(input))

Upvotes: 5

Related Questions