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
.
R has overloaded the double equals
==
operator with a method of finding the index of a needle in a vector haystack. It yields alogical
vector, containingTRUE
values for each match in the haystack.Example:
It works if both are vectors, and can be expanded to use multiple vectors as well.
The function
match
works on vectors :match
only returns the first encounter of a match, as you requested. It returns the position in the second argument of the values in the first argument.For multiple matching,
%in%
is the way to go :%in%
returns a logical vector as long as the first argument, with aTRUE
if that value can be found in the second argument and aFALSE
otherwise.A small note about the efficiency of abovementioned methods:
So, the best one is
the function
Position
in funprog {base} also does the job. It allows you to pass an arbitrary function, and returns the first or last match.Position(f, x, right = FALSE, nomatch = NA_integer)