Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to pass arguments as a list in R function

I have functions that has a lot of arguments. So I would like to create a list of arguments and pass them to the function.

As an example, take ?mean function:

mean(x, trim = 0, na.rm = FALSE, ...)

So lets say I want to calculate mean of 1:10, assigned to variable x, but pass other arguments as a list:

gm <- list (trim = 0, na.rm = FALSE)

mean(1:10, gm)
#R> Error in mean.default(1:10, gm) : 'trim' must be numeric of length one

I tried to use do.call but do not work either.

do.call(mean,list(1:10, gm))
#R> Error in mean.default(1:10, list(trim = 0, na.rm = FALSE)) : 
#R>   'trim' must be numeric of length one
like image 906
SHRram Avatar asked Oct 09 '14 03:10

SHRram


1 Answers

As noted in a comment, your gm has the wrong shape for do.call, it interprets your option list as a trim argument.

To make the argument correct shape, use c:

gm <- list(trim=0, na.rm=FALSE)
do.call(mean, c(list(1:10), gm))
[1] 5.5
like image 112
sds Avatar answered Oct 07 '22 15:10

sds