D Pinto D Pinto - 4 years ago 150
R Question

Pass rows of a data frame as arguments to a function in R with column names specifying the arguments

I want to use the rows of a dataframe as arguments for a function. I know this can be done like this:

arg <- expand.grid(n = 100, mean = -1:1, sd = 0:3)

apply(arg, 1, FUN = function(x) rnorm(x[1], x[2], x[3]))


I would like, however, to have a more general, elegant way to pass the arguments using the column names of a dataframe to specify them (if the colum names is not an option, the order of the columns will do it as well).

I don't want to specify in every function which column refers to each argument, as I have done in the example above. Also, I would like to pass the values to functions with arbitrary number of arguments.

Answer Source

We can use Map

do.call(Map, c(f= rnorm, arg))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download