Dan Lewer
Dan Lewer

Reputation: 956

Using mapply where the arguments are specified by a data frame

I am trying to use a function lots of times and vary the arguments each time. The arguments I want to vary also change.

I am trying to use a data frame where the column names specify which arguments I want to change.

For example, imagine we are using mapply to multiple 1:3 by 4 and 5:

f <- function(A, B, C = 1) A * B * C
mapply(f, A = rep(1:3, 2), B = rep(4:5, each = 3))

We can use expand.grid to make things easier:

arg <- expand.grid(A = 1:3, B = 4:5)
mapply(f, A = arg$A, B = arg$B)

I am trying to do this:

mapply(f, arg)

Such that the arguments A and B are specified in the input arg. Is this possible?

Upvotes: 1

Views: 163

Answers (1)

akrun
akrun

Reputation: 887158

We can use do.call

do.call(Map, c(f = f, arg))

Or with mapply

do.call(mapply, c(FUN = f, arg))
#[1]  4  8 12  5 10 15

Upvotes: 2

Related Questions