是否有R函数用于查找向量中元素的索引? [英] Is there an R function for finding the index of an element in a vector?
问题描述
在R中,我有一个元素 x
和一个向量 v
。我想找到 v
中元素的第一个索引,它等于 x
。我知道这样做的一种方法是:哪个(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
是一个向量?也就是说,它应该在 v
中返回一个索引向量,表示 x
中每个元素的位置。
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
.
推荐答案
函数匹配
适用于向量:
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屋!