I want to pass a list to partially match a function's parameters. I am looking for syntax of equivalent simplicity as the do.call
method here: Passing list of named parameters to function?
Here is an example (taken from https://stackoverflow.com/a/15059219/2109289), where calling mapply(FUN, ...)
requires the data frame columns to be passed one by one to ...
:
> df <- data.frame(x=c(1,2), y=c(3,4), z=c(5,6))
> df
x y z
1 1 3 5
2 2 4 6
> mapply(function(x,y) x+y, df$x, df$z)
[1] 6 8
Wouldn't it be nice if you could just pass the data frame df[, c("x", "z")]
as an argument?
E.g.:
df <- data.frame(x=c(1,2), y=c(3,4), z=c(5,6))
do.call(function(x, y) mapply(function(x,y) x+y, x, y), unname(df[, c("x", "z")]))
# [1] 6 8
do.call(function(...) mapply(function(x,y) x+y, list(...)[[1]], list(...)[[2]]), df[, c("x", "z")])
# [1] 6 8
Is there a better way of doing this instead of creating a closure to be passed to do.call
?