[R] Subsetting a list of vectors

Spencer Graves spencer.graves at pdf.com
Mon Nov 10 02:08:36 CET 2003


When I did it in S-Plus 6.1 and R 1.8.0, I didn't get NULL entries:  I 
got NAs.  There is a difference between NULLs and NAs.  The NAs can be 
deleted using is.na, as follows: 

 > list.of.vectors <- list(a=1, b=1:3)
 > x3 <- sapply(list.of.vectors, function(x)x[3])
 > x3
 a  b
NA  3
 > x3
 a  b
NA  3
 > x3[!is.na(x3)]
b
3
 >
Is this acceptable? 
spencer graves

Hadley Wickham wrote:

> Hi,
>
> I'm trying to subset a list which contains variable length vectors.  
> What I want to do is extract (eg.) the 3rd item in each vector (with 
> length >= 3).  At the moment I'm using sapply(list.of.vectors, 
> function(x) {x[3]}).  The problem with this is that sapply returns a 
> list of the same length of list.of.vectors so I end up with a whole 
> lot of null entries from those vectors that aren't long enough.  I 
> have a similar problem if I want to select all the vectors where the 
> 3rd item is a specified value.
>
> Does anyone have any better solutions?
>
> Thanks for you help,
>
> Hadley
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://www.stat.math.ethz.ch/mailman/listinfo/r-help




More information about the R-help mailing list