I came to this question trying to figure out how to save a configuration of parameters that you would have passed into a function, and pass them on demand in a different line. The question and top answer weren't initially clear to me, so I have a simple demonstration for those just starting to learn R.
Let's say for example that you have the function substr that takes parameters x, start, and stop.
Instead of calling substr("Hello World", 2, 5) to get "ello", we can save the parameters into a list and call the function with the parameters using do.call:
params <- list("Hello World", 2, 5)
do.call(substr, params)
>> "ello"
If you only want to save start and stop, you can prepend the first argument with the combine function c:
params <- list(2, 5)
do.call(substr, c("Hello World", params))
>> "ello"
You can also add named arguments to the list the same way you specify parameters in a function call:
params <- list(stop=5, x="Hello World", start=2)
do.call(substr, params)
>> "ello"
And the list can mix named and non-named parameters:
params <- list("Hello World", start=2, stop=5)
do.call(substr, params)
>> "ello"
If you need more complex logic, you can also wrap your call in a factory function:
make_substr <- function(start, stop){
return(
function(string) {
substr(string, start, stop)
}
)
}
substr_2_5 <- make_substr(2, 5)
substr_2_5("Hello World")
>> "ello"
substr_2_5("Goodbye")
>> "oodb"