Basic question (if you know the answer)... I am dealing with a list of commonly-formatted sub-lists, for example: l <- list("") l[[1]] <- c("A1","A2","A3") l[[2]] <- c("B1","B2","B3") l[[3]] <- c("C1","B2","B3") Lets say I need to extract every 2nd item (i.e. A2, B2, C2). [[]] cannot be used. l[2] returns practically the same as l[[2]]. Is there a way to achieve this without having to loop or convert to data.frame? Thanks in advance. -- View this message in context: http://r.789695.n4.nabble.com/Selecting-elements-from-all-items-in-a-list-tp4387045p4387045.html Sent from the R help mailing list archive at Nabble.com.
How about: l <- list("") l[[1]] <- c("A1","A2","A3") l[[2]] <- c("B1","B2","B3") l[[3]] <- c("C1","B2","B3") lapply(l, "[[", 2) or sapply(l, "[[", 2) I hope it helps. Best, Dimitris On 2/14/2012 2:44 PM, geotheory wrote:> Basic question (if you know the answer)... I am dealing with a list of > commonly-formatted sub-lists, for example: > > l<- list("") > l[[1]]<- c("A1","A2","A3") > l[[2]]<- c("B1","B2","B3") > l[[3]]<- c("C1","B2","B3") > > Lets say I need to extract every 2nd item (i.e. A2, B2, C2). [[]] cannot be > used. l[2] returns practically the same as l[[2]]. Is there a way to > achieve this without having to loop or convert to data.frame? > > Thanks in advance. > > -- > View this message in context: http://r.789695.n4.nabble.com/Selecting-elements-from-all-items-in-a-list-tp4387045p4387045.html > Sent from the R help mailing list archive at Nabble.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. >-- Dimitris Rizopoulos Assistant Professor Department of Biostatistics Erasmus University Medical Center Address: PO Box 2040, 3000 CA Rotterdam, the Netherlands Tel: +31/(0)10/7043478 Fax: +31/(0)10/7043014 Web: http://www.erasmusmc.nl/biostatistiek/
On Feb 14, 2012, at 8:44 AM, geotheory wrote:> Basic question (if you know the answer)... I am dealing with a list > of > commonly-formatted sub-lists, for example: > > l <- list("") > l[[1]] <- c("A1","A2","A3") > l[[2]] <- c("B1","B2","B3") > l[[3]] <- c("C1","B2","B3") > > Lets say I need to extract every 2nd item (i.e. A2, B2, C2). [[]] > cannot be > used. l[2] returns practically the same as l[[2]]. Is there a way > to > achieve this without having to loop or convert to data.frame?Any such extraction would of necessity have a loop-like basis, but perhaps you meant without an explicit for-loop? > sapply(l, "[[", 2) [1] "A2" "B2" "B2" -- David Winsemius, MD West Hartford, CT
Yes the lapply function sorted it out. Thanks for the advice. -- View this message in context: http://r.789695.n4.nabble.com/Selecting-elements-from-all-items-in-a-list-tp4387045p4387505.html Sent from the R help mailing list archive at Nabble.com.