Finding All Positions for Multiple Elements in a Vector


Question

Suppose I have the following vector:

x <- c(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?

1
21
8/17/2018 8:01:05 AM

Accepted Answer

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
37
7/23/2009 3:13:38 AM

You could try the | operator for short conditions

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

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon