On Jul 3, 2014, at 2:35 PM, carol white <wht_...@yahoo.com> wrote:

> Hi,
> Is there any way to access an element of a list without looping over the list 
> nor using unlist? Just to avoid parsing a very long list.
> 
> 
> For ex, how to find a vector of a length 2 in a list without using a loop?
> 
> l = list (c(1), c(2,3), c(1,2,3))
> for (i in 1:length(l))
>     if(length(l[[i]]==2){
>         print (i)
>         break
>     }
> 
> Thanks
> 
> Carol


You can use one of the *apply() functions, albeit, it is still effectively 
looping through the list. It may or may not be faster in some cases than an 
explicit for() loop, but it can be easier to read, depending upon the 
complexity of the function being utilized within the call.

For example:

> which(sapply(l, function(x) length(x) == 2))
[1] 2

This presumes that you only have a single level of list elements to scan. If 
you have "sub-levels" within the list, you might want to look at ?rapply, which 
is a recursive version.

Regards,

Marc Schwartz

______________________________________________
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.

Reply via email to