[R] Selecting all rows of factors which have at least one positive value?

hadley wickham h.wickham at gmail.com
Fri Apr 3 04:34:31 CEST 2009


>   X1 X2
> 1  11  0
> 2  11  0
> 3  11  0
> 4  11  1
> 5  12  0
> 6  12  0
> 7  12  0
> 8  13  0
> 9  13  1
> 10 13  1
>
>
> and I want to select all rows pertaining to factor levels of X1 for
> which exists at least one "1" for X2. To be clear, I want rows 1:4
> (since there exists at least one observation for X1==11 for which
> X2==1) and rows 8:10 (likewise).
>
> It is easy to obtain the corresponding factor levels (i.e.,
> unique(x$X1[x$X2==1])), but I got stalled selecting the corresponding
> rows. I tried grep, but then I have to loop and concatenate the
> resulting vector. Any ideas?

Here's one way using plyr:

library(plyr)
ddply(x, "X1", subset, any(X2 == 1))

See http://had.co.nz/plyr for more details.

Hadley


-- 
http://had.co.nz/




More information about the R-help mailing list