# [R] confused with vector subsetting

Thomas Lumley tlumley at u.washington.edu
Fri Jul 5 18:51:25 CEST 2002

```On Fri, 5 Jul 2002, Laurent Gautier wrote:

> Dear all,
>
> I do not know whether the following results from an obscure feature
> of R or from my misunderstanding.
>
> > x <- 1:3
> > x[-which(x == 2)]
> [1] 1 3
> > x[-which(x == 4)]
> numeric(0)
> (I would have expected something like '[1] 1 2 3' at that point)
>

It's a pity that this doesn't work, but it can't.

Since which(x==4) is numeric(0), -which(x==4) is also numeric(0), so R
can't possibly distinguish between
x[-which(x == 4)]
x[ which(x == 4)]
so they can't both do what you would like

If you don't know whether 4 will appear in x you need to do
x[!(x==4)]
or preferably
x[!(x %in% 4)]
which will work even if x contains NAs.

-thomas

-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._

```