[R] How to pass a list of parameters into a function

Barry Rowlingson b.rowlingson at lancaster.ac.uk
Mon Apr 19 19:16:48 CEST 2010


On Mon, Apr 19, 2010 at 5:58 PM, Gene Leynes <gleynes+r at gmail.com> wrote:
> Does anyone know how to pass a list of parameters into a function?
>
>
> for example:
>
> somefun=function(x1,x2,x3,x4,x5,x6,x7,x8,x9){
>    ans=x1+x2+x3+x4+x5+x6+x7+x8+x9
>    return(ans)
> }
>
> somefun(1,2,3,4,5,6,7,8,9)
>
> # I would like this to work:
> temp=c(x3=3,x4=4,x5=5,x6=6,x7=7,x8=8,x9=9)
> somefun(x1=1,x2=2,temp)
>
> # OR I would like this to work:
> temp=list(x3=3,x4=4,x5=5,x6=6,x7=7,x8=8,x9=9)
> somefun(x1=1,x2=2,temp)

 Why?

 These are the kind of things that should only be done by people who
know how to do them and hence know not to do them. A bit like the
definition of a gentleman being someone who knows how to play the
bagpipes but chooses not to.

 You can do this, but it requires all sorts of fiddling of the
argument lists which would make the functions very messy, and most
probably unlike any other R functions the user has encountered.

 But... for starters you might want to look at the '...' argument
which gives some flexibility in argument handling, something like:

 foo = function(...){
   return(list(...))
}

 then try foo(x1=1,x2=2) and so on. See what you get back. Then work
out how to add them all up, check they are all x1 to x9 and so on. And
recursively unwrap your 'temp' variable by testing if it is atomic or
not.

 I'm off to play the bagpipes now.

Barry



More information about the R-help mailing list