[R] Why does a[which(b == c[d])] not work?

Gabor Grothendieck ggrothendieck at myway.com
Wed Oct 8 18:38:28 CEST 2003


Here are some different ways of doing this. Don't know whether any
could be considered superior to the others.

# y[x==5] regarding NAs in x as not matching
x <- c(5, NA, 7, 5, NA, 3)
y <- c(1,  2, 3, 4,  5, 6)
subset(y,x==5)
y[x %in% 5]
y[x %in% c(5)]
y[which(x==5)]


--- 
Date: Wed, 08 Oct 2003 08:58:32 -0600 
From: Tony Plate <tplate at blackmesacapital.com>
 
At Wednesday 03:06 PM 10/8/2003 +0200, Martin Maechler wrote:
>Your question has been answered by Achim and Peter Dalgaard (at least).
>
>Just a note:
>
>Using
> a[which(logic)]
>looks like a clumsy and inefficient way of writing
> a[ logic ]
>
>and I think you shouldn't propagate its use ...

What then is the recommended way of treating an NA in the logical subset as 
a FALSE? (Or were you just talking about the given example, which didn't 
have this issue. However, you admonition seemed more general.)

As in:
> x <- 1:4
> y <- c(1,2,NA,4)
> x[y %% 2 == 0]
[1] 2 NA 4
> x[which(y %% 2 == 0)]
[1] 2 4
>

Sometimes one might want the first result, but more usually, I want the 
second, and using which() seems a convenient way to get it.

-- Tony Plate


_______________________________________________
No banners. No pop-ups. No kidding.
Introducing My Way - http://www.myway.com




More information about the R-help mailing list