Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace the argument with a list in R [duplicate]

Some times there is a function which has an arbitrary number of arguments. For example, the bootstrapPage function of package shiny. If I have a data.frame and I want to create one widget for one row, then I have not figured out a pretty way to pass the number of arguments according to the row number of the data.frame. So far, I generate the script and use the trick of eval(parse(text="..."))

In fact, the structure of arguments passed to function in R (key and value) is similar to a list, so I am wondering if there is a way to pass the argument as a list in R.

More specifically, if I have a function f and a list argv, is there a way to pass the objects in argv to f according to the matching of the name of argv and the name of the arguments of f, and the position in argv and the position in the arguments of f?

For example, let

f <- function(a, b) a + b
argv <- list(a=1, b=2)

How should I pass the argv to f which is equivalent to f(a=argv$a, b=argv$b)?

Or if we have:

f <- function(a, b, ...) { # some codes }
argv <- list(a = 1, b = 2, 3, 4, 5)

How should I pass the argv to f which is equivalent to f(a=argv$a, b=argv$b, argv[[3]], argv[[4]], argv[[5]])?

Thanks!

like image 422
wush978 Avatar asked Mar 09 '13 17:03

wush978


1 Answers

You are looking for do.call.

do.call(f, argv)

Here are some examples

> args <- list(n = 10, mean = 3, sd = .5)
> do.call(rnorm, args)
 [1] 3.589416 3.393031 2.928506 2.503925 3.316584 2.581787 2.686507 3.178877
 [9] 3.083885 2.821506
> do.call(rnorm, list(10, 3, .5))
 [1] 3.964526 2.838760 2.436684 3.068581 1.842332 3.739046 4.050525 3.097042
 [9] 3.665041 3.535947
> f <- function(a, b) a + b
> argv <- list(a=1, b=2)
> do.call(f, argv)
[1] 3
> f <- function(a, b, ...){print(a);print(b);print(sum(...))}
> argv <- list(a=1,b=2, 3, 4, 5)
> do.call(f, argv)
[1] 1
[1] 2
[1] 12
like image 139
Dason Avatar answered Nov 20 '22 11:11

Dason