[R] Passing lists between functions

Rolf Turner rolf.turner at xtra.co.nz
Mon Nov 26 03:05:48 CET 2012


On 26/11/12 14:24, Ally wrote:
> I'd like to pass a list object created by one function as an argument of
> another function.  once inside the second function, I'd like to break the
> list up to it's individual elements, each then identifiable by the 'names'
> of the list.
>
> The list looks something like
>
> lst<-list(a=1, b=2, df=5, g=7)
>
> then inside the function I've been writing a sequence of statements that
> extract the objects within lst like
>
> do_something<-function(L){
> a<-lst$a
> b<-lst$b
> df<-lst$df
> g<-lst$g
> a+b+df+g
> }

     Did you mean to write "L" in the foregoing where you have written 
"lst"?
> do_something(lst)
>
> My question is, is it possible to avoid the above sequence of statements,
> and achieve the same thing with a single line of code?  Perhaps this would
> be bad programming practise, as you can't 'see' where objects in the
> function are coming from?

     Perhaps:

     do_something <- function(L){
         with(L,a+b+df+g)
     }

         cheers,

             Rolf Turner




More information about the R-help mailing list