Is there an R function for finding the index of an element in a vector?
Asked 07 September, 2021
Viewed 2.4K times
  • 54
Votes

In R, I have an element x and a vector v. I want to find the first index of an element in v that is equal to x. I know that one way to do this is: which(x == v)[[1]], but that seems excessively inefficient. Is there a more direct way to do it?

For bonus points, is there a function that works if x is a vector? That is, it should return a vector of indices indicating the position of each element of x in v.

4 Answer