0

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?

Alex
  • 15,186
  • 15
  • 73
  • 127

1 Answers1

2

One option would be

unlist(do.call(Map, c(f = `+`, df[c('x', 'z')])))
#[1] 6 8

Or using mapply

do.call(mapply, c(FUN = `+`, df[c('x', 'z')]))
#[1] 6 8
akrun
  • 874,273
  • 37
  • 540
  • 662
  • 1
    or `do.call("+", df[, c("x", "z")])` – baptiste Nov 03 '17 at 06:14
  • @baptiste or `Reduce('+', df[c('x', 'z')])` – akrun Nov 03 '17 at 06:16
  • Thanks, looks useful, but I am not sure how this will hold up for a more general function. I.e., for a general function `f <- function(x1, x2, x3, ...)`, be able to call it like `f(x1, x2, arg_list)`. – Alex Nov 03 '17 at 06:24
  • @Alex The `f` or `FUN` takes a function as argument. So, I don't know what is the problem here. – akrun Nov 03 '17 at 06:26
  • my problem is that to use a list in a function, either explicitly call each element of the list for each function parameter, or, create a complete list of function arguments to be then passed to `do.call` (your second solution). I am wondering whether there is a middle ground where you don't have to do this. – Alex Nov 03 '17 at 06:29
  • @Alex If you have a different problem, then the question should have been different. Here, I am answering the question you posted. Also, you must have noticed that the `+` can be called more easier than with `mapply` (from the comments) – akrun Nov 03 '17 at 06:30
  • I will think about this a bit more and edit the question. Thanks. – Alex Nov 03 '17 at 06:30