tags:

views:

292

answers:

4

Suppose I have the following vector:

> x <- sample(1:10,20,replace=TRUE)
> x
 [1]  8  6  9  9  7  3  2  5  5  1  6  8  5  2  9  3  5 10  8  2

How can I find which elements are either 8 or 9?

+5  A: 

This is one way to do it. First I get the indices at which x is either 8 or 9. Then we can verify that at those indices, x is indeed 8 and 9.

> inds <- which(x %in% c(8,9))
> inds
[1]  1  3  4 12 15 19
> x[inds]
[1] 8 9 9 8 9 8
Christopher DuBois
A: 

Alternatively, if you do not need to use the indices but just the elements you can do

> x <- sample(1:10,20,replace=TRUE)
> x
 [1]  6  4  7  2  9  3  3  5  4  7  2  1  4  9  1  6 10  4  3 10
> x[8<=x & x<=9]
[1] 9 9
Yann Abraham
+2  A: 

which(x == 8 | x == 9)

A: 

grepl maybe a useful function. Note that grepl appears in versions of R 2.9.0 and later. What's handy about grepl is that it returns a logical vector of the same length as x.

grepl(8, x)

[1] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE [13] FALSE FALSE FALSE TRUE FALSE FALSE FALSE FALSE

grepl(9, x)

[1] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE TRUE FALSE [13] FALSE FALSE FALSE FALSE TRUE FALSE FALSE TRUE

To arrive at your answer, you could do the following

grepl(8,x) | grepl(9,x)

andrewj