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
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.
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