[R] Subsetting a list of vectors

Dirk Eddelbuettel edd at debian.org
Mon Nov 10 04:47:06 CET 2003


On Sun, Nov 09, 2003 at 09:29:26PM -0600, Dirk Eddelbuettel wrote:
> On Sun, Nov 09, 2003 at 10:00:42PM -0500, Gabor Grothendieck wrote:
> > 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 ]
> 
> ifelse is your friend:
> 
> > sapply( 1:10, function(x) ifelse(x%%2, 0, x)^2 )
> [1]   0   4   0  16   0  36   0  64   0 100

PS: if you want just the set, maybe flagging as NA would do:

> as.numeric(na.omit(sapply( 1:10, function(x) ifelse(x%%2,NA,x)^2 )))
[1]   4  16  36  64 100

but that is indeed still not as clever as the loop-condiional from Python.

Dirk

-- 
Those are my principles, and if you don't like them... well, I have others.
                                                -- Groucho Marx




More information about the R-help mailing list