[R] How to get the names of list elements when iterating over alist?
William Dunlap
wdunlap at tibco.com
Wed Nov 11 17:49:00 CET 2009
> -----Original Message-----
> From: r-help-bounces at r-project.org
> [mailto:r-help-bounces at r-project.org] On Behalf Of Peng Yu
> Sent: Wednesday, November 11, 2009 8:02 AM
> To: r-help at stat.math.ethz.ch
> Subject: [R] How to get the names of list elements when
> iterating over alist?
>
> I need to get the names of the list elements when I iterate over a
> list. I'm wondering how to do so?
>
> alist=list(a=c(1,3),b=c(-1,3),c=c(-2,1))
> sapply(alist,function(x){
> #need to use the name of x for some subsequent process
> })
sapply(X,FUN) and lapply(X,FUN) do the equivalent of
for(i in seq_along(X))
FUN(X[[i]])
X[[i]] represents i'th elemenent of the list X,
not a list containing the i'th element. Hence the name
from the original list X is not part of X[[i]]. If FUN
expects a named list of length 1 then you can do
sapply(seq_along(X), function(i)FUN(X[i]))
or write your own for loop
for(i in seq_along(X))
FUN(X[i])
If FUN wants the name as a separate argument you could do
sapply(seq_along(X), function(i)FUN(X[[i]], names(X)[i]))
or you could write the equivalent loop by hand.
Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com
>
> ______________________________________________
> 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.
>
More information about the R-help
mailing list