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
.
This question is related to
r
indexing
match
vectorization
A small note about the efficiency of abovementioned methods:
library(microbenchmark)
microbenchmark(
which("Feb" == month.abb)[[1]],
which(month.abb %in% "Feb"))
Unit: nanoseconds
min lq mean median uq max neval
891 979.0 1098.00 1031 1135.5 3693 100
1052 1175.5 1339.74 1235 1390.0 7399 100
So, the best one is
which("Feb" == month.abb)[[1]]
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)
Source: Stackoverflow.com