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
.
which(x == v)[[1]]
is not so very inefficient. It's one comparison (==
) operator applied to all vector elements and one subsetting on the indices (which
). That's it. Nothing that should be relevant, as long as you're not running 10.000 repetitions on this function. Other solutions likematch
andPosition
may not return as many data aswhich
, but they're not necessarily more efficient. – BurninLeowhich(x == v)[[1]]
is not. – Ryan C. Thompson