Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a list() to an ellipsis in R?

Tags:

r

Suppose I have two functions using three dots constructs for their arguments.

I want to retrieve the ellipsis of the first function and create a brand new list of arguments for the second function.

How can I pass the newly created list to the second function?

Here is a sample code:

first.function <- function(..., name) {
  argument.list <- list(...)

  new.args <- list()
  for (i in 1:length(argument.list)) {
    new.args[[i]] <- argument.list[[i]]^2
  }
  new.args[[length(new.args) + 1]] <- name

  do.call(second.function, new.args)
}

second.function <- function(..., name) {
  print(paste("This is the name:", name))
  print(paste("These are the arguments:", ...))
}

first.function(1, 2, 3, name = "Test")

I tried with do.call, but I have an error message:

Error in paste("This is the name:", name) : argument "name" is missing, with no default

This is because the second function does not recognize the name argument as a separate argument from the ellipsis arguments.

The expected result is:

This is the name: Test

These are the arguments: 1, 4, 9

like image 759
Ben Avatar asked May 09 '16 14:05

Ben


1 Answers

Just name the parameter:

first.function <- function(..., name) {
  argument.list <- list(...)

  new.args <- lapply(argument.list, `^`, 2) 
  new.args[["name"]] <- name

  do.call(second.function, new.args)
}

first.function(1, 2, 3, name = "Test")
#[1] "This is the name: Test"
#[1] "These are the arguments: 1 4 9"

Here is a link to the relevant section of the language definition: 4.3.2 Argument matching.

like image 192
Roland Avatar answered Sep 28 '22 09:09

Roland