Search code examples
rvectorr-faq

Finding All Positions for Multiple Elements in a Vector


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?


Solution

  • 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