[R] Subsetting a list of vectors

Dirk Eddelbuettel edd at debian.org
Mon Nov 10 04:29:26 CET 2003


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