[R] Subsetting a list of vectors

Gabor Grothendieck ggrothendieck at myway.com
Mon Nov 10 04:00:42 CET 2003

This has already been answered but I think behind your 
question may have been the thought of whether its 
possible to do it all at once: transformation and selection.

There are languages that do allow this.  For example, Python 
has list comprehensions which are things like this:

   # 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]

In R you could do this:

	sapply( 1:10, function(x)x^2 )

but AFAIK you can't incorporate the condition without creating 
a temporary:

	t <- sapply( 1:10, function(x)x^2 )
	z <- t[ t%%2 == 0 ]

(In this simple example we could have used the fact that parity
is invariant under squaring to reduce 1:10 to seq(2,10,2)
and thereby eliminate the selection part but that's not really
the point since that avoids the problem rather than allowing its
expression in the terms we want.)

Date: Mon, 10 Nov 2003 13:43:07 +1300 
From: Hadley Wickham <h.wickham at auckland.ac.nz>
To: R-Help Mailing List <r-help at stat.math.ethz.ch> 
Subject: [R] Subsetting a list of vectors 


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,


More information about the R-help mailing list