[R] lapply and list attributes

Seth Falcon sfalcon at fhcrc.org
Fri Mar 10 16:41:36 CET 2006


Hi,

"michael watson (IAH-C)" <michael.watson at bbsrc.ac.uk> writes:
> I have a list that has attributes:
>
> attributes(lis[2])
> $names
> [1] "150096_at"
>
> I want to use those attributes in a function and then use lapply to
> apply that function to every element of the list, eg for simplicity's
> sake:
>
> my.fun <- function(x) {
>         attributes(x)
> }

This gets tricky.  You said the right thing: you have a _list_ with
attributes.  This does not mean the elements of the list have
attributes (unless they happen to). 

> It seems that "attributes(x)" within the function is not the same as eg.
> "attributes(lis[2])" used outside of the function, ie the attributes
> have changed.

"[" on a list returns a sublist (with names copied over).  The lapply
function is equivalent to accessing elements via "[[" which pulls out
a single element (no names).

For the specific case of processing a list with names, you may want:

for (name in names(x)) {
   el <- x[[name]]
   ...
}

You could also try mapply.

+ seth




More information about the R-help mailing list