是否有用于查找向量中元素索引的 R 函数? [英] Is there an R function for finding the index of an element in a vector?
问题描述
在 R 中,我有一个元素 x
和一个向量 v
.我想在 v
中找到一个元素的第一个索引,它等于 x
.我知道这样做的一种方法是:which(x == v)[[1]]
,但这似乎效率太低了.有没有更直接的方法?
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?
对于奖励积分,如果 x
是向量,是否有一个函数有效?也就是说,它应该返回一个索引向量,指示 x
的每个元素在 v
中的位置.
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
.
推荐答案
match
函数作用于向量:
x <- sample(1:10)
x
# [1] 4 5 9 3 8 1 6 10 7 2
match(c(4,8),x)
# [1] 1 5
match
仅根据您的要求返回匹配的第一次遇到.它返回第一个参数中的值在第二个参数中的位置.
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.
对于多重匹配,%in%
是要走的路:
For multiple matching, %in%
is the way to go:
x <- sample(1:4,10,replace=TRUE)
x
# [1] 3 4 3 3 2 3 1 1 2 2
which(x %in% c(2,4))
# [1] 2 5 9 10
%in%
返回一个与第一个参数相同的逻辑向量,如果可以在第二个参数中找到该值,则返回一个 TRUE
和一个 FALSE
否则.
%in%
returns a logical vector as long as the first argument, with a TRUE
if that value can be found in the second argument and a FALSE
otherwise.
这篇关于是否有用于查找向量中元素索引的 R 函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!