Hi, You can also use: jlist[unlist(lapply(jlist,length))>0] #[[1]] #[1] 1 0
#[[2]] #[1] 1 2 3 A.K. ________________________________ From: Gonçalo Ferraz <gferra...@gmail.com> To: arun <smartpink...@yahoo.com> Sent: Thursday, November 8, 2012 9:59 AM Subject: Re: [R] Accessing selected elements of a list Thanks! I think one quick solution (from another answer that just arrived) is: jlist[ sapply(jlist,length) > 0 ] G. On Nov 8, 2012, at 10:57 AM, arun wrote: Hi, >If i understand it correctly, > >lapply(jlist,function(x) x[x>0]) >#[[1]] >#NULL > >#[[2]] >#[1] 1 > >#[[3]] >#NULL > >#[[4]] >#[1] 1 2 3 > >#[[5]] >#NULL >A.K. > > > >----- Original Message ----- >From: Gonçalo Ferraz <gferra...@gmail.com> >To: r-help@r-project.org >Cc: >Sent: Thursday, November 8, 2012 9:42 AM >Subject: [R] Accessing selected elements of a list > >Hi, > > >If I have a vector: > >junk <- c(2,0,0,3,0) > >and want to access, say, all the elements that are greater than zero. I just >do: > >junk[which(junk>0)] > > > >Now, If I have a list: > >jlist <- list(NULL,c(1,0),NULL,c(1,2,3), NULL) > >and want to access all the elements that have length greater than zero, I know >how to find the elements with: > >which(sapply(jlist,length)>0) > >But how do I get a new list, only with the non-zero-length elements, without >having to write a for loop? > >I tried: > >notnull <- which(sapply(jlist,length)>0) >jlist[[notnull]] > >and got the error: > >Error in jlist[[notnull]] : recursive indexing failed at level 2 > >Thank you for any help! > >______________________________________________ >R-help@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. > > Gonçalo Ferraz, PhD Biological Dynamics of Forest Fragments Project Smithsonian Tropical Research Institute / Instituto Nacional de Pesquisas da Amazônia http://ferrazlab.com/LabSite/Welcome.html Endereço Postal / Postal Address: PDBFF - INPA, CP 478, Av. André Araújo, 2936, 69060-000 Manaus AM, Brasil Tel: 55 (92) 3642-1148 ______________________________________________ R-help@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.