[R] Subsetting a list of vectors
ggrothendieck at myway.com
Mon Nov 10 06:23:17 CET 2003
Dirk and Ray have provided two very clever solutions which
perform transformation and selection in one go
by returning NA and NULL respectively for unwanted elements
and then eliminating the NAs and NULLs.
I thought it would be worthwhile to bring them together and
make some further minor improvements.
Note that for the NULL solution we use the fact that
if(FALSE)... with no else leg equals NULL.
Problem 1. If v is a list of vectors, get the vector which is the
third element of each vector in v. Do not include any elements
for vectors with less than 3 elements.
Here the NA solution is particularly short:
as.numeric( na.omit( sapply( v, "[", 3 ) ) )
but the NULL solution seems closer to the list comprehension idea:
unlist( sapply( v, function(x) if (length(x)>=3) x ) )
Problem 2. Express this Python program in R:
# give me the squares of the even numbers from 1-10, in a list.
>>> [ x*x for x in range(1,11) if x%2 == 0]
Here the NULL Solution is both short and closer to the Python one:
unlist( sapply( 1:10, function(x) if (x%%2==0) x^2 ) )
while the NA solution is:
as.numeric(na.omit(sapply(1:10,function(x)if(x%%2==0)x^2 else NA)))
More information about the R-help