[R] Accessing selected elements of a list

jim holtman jholtman at gmail.com
Thu Nov 8 15:53:11 CET 2012


try this (use '[' for indexing)

> jlist <- list(NULL,c(1,0),NULL,c(1,2,3), NULL)
> jlist
[[1]]
NULL

[[2]]
[1] 1 0

[[3]]
NULL

[[4]]
[1] 1 2 3

[[5]]
NULL

> which(sapply(jlist, length) > 0)
[1] 2 4
> jlist[sapply(jlist, length) > 0]
[[1]]
[1] 1 0

[[2]]
[1] 1 2 3

>


On Thu, Nov 8, 2012 at 9:42 AM, Gonçalo Ferraz <gferraz29 at gmail.com> wrote:
> 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 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.



-- 
Jim Holtman
Data Munger Guru

What is the problem that you are trying to solve?
Tell me what you want to do, not how you want to do it.




More information about the R-help mailing list