[R] get list element names within lapply / sapply call

David Winsemius dwinsemius at comcast.net
Sat Jan 15 23:37:09 CET 2011


On Jan 15, 2011, at 4:06 PM, Jonathan Flowers wrote:

> Hi all,
>
> I would like to iterate through a list with named elements and  
> access the
> names within an lapply / sapply call. One way to do this is iterate  
> through
> the names and index the list with the name.  Is there a way to iterate
> through the list elements themselves and access the element names  
> within in
> the function? For example,
>
> mylist <- list("a"=c(1,2),"b"=c(3,4),"c"=c(5,6))
> sapply(mylist,function(x){
>  #get name of list elements ("a", "b", "c")
>  #then do other stuff
> })

You can pass this result to "[[":
 > names(sapply(mylist, names))
[1] "a" "b" "c"

 > sapply( names(sapply(mylist, names)) , function(x) mylist[[x]]^2)
      a  b  c
[1,] 1  9 25
[2,] 4 16 36


>
> Thanks for your suggestions.
>
> Jonathan
>
> 	[[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list