Peng Yu
2009-Nov-11 16:02 UTC
[R] How to get the names of list elements when iterating over a list?
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 })
William Dunlap
2009-Nov-11 16:49 UTC
[R] How to get the names of list elements when iterating over alist?
> -----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. >
Possibly Parallel Threads
- how to search a list that contains multiple dissimilar vectors?
- Extracting multiple elements from a list
- Is there an variant of apply() that does not return anything?
- Bug or feature with finding a list element?
- How to speed up multiple for loop over list of data frames