[英]Is there an R function for finding the index of an element in a vector?
In R, I have an element x
and a vector v
.在 R 中,我有一个元素
x
和一个向量v
。 I want to find the first index of an element in v
that is equal to x
.我想找到
v
中等于x
的元素的第一个索引。 I know that one way to do this is: which(x == v)[[1]]
, but that seems excessively inefficient.我知道这样做的一种方法是:
which(x == v)[[1]]
,但这似乎效率极低。 Is there a more direct way to do it?有没有更直接的方法呢?
For bonus points, is there a function that works if x
is a vector?对于奖励积分,如果
x
是向量,是否有 function 有效? That is, it should return a vector of indices indicating the position of each element of x
in v
.也就是说,它应该返回一个索引向量,指示
v
中x
的每个元素的 position。
The function match
works on vectors:函数
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
only returns the first encounter of a match, as you requested. match
仅根据您的要求返回match
的第一次遇到。 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%
是要走的路:
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%
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. %in%
返回一个与第一个参数一样长的逻辑向量,如果可以在第二个参数中找到该值,则为TRUE
,否则为FALSE
。
the function Position
in funprog {base} also does the job. funprog {base} 中的函数
Position
也可以完成这项工作。 It allows you to pass an arbitrary function, and returns the first or last match.它允许您传递任意函数,并返回第一个或最后一个匹配项。
Position(f, x, right = FALSE, nomatch = NA_integer)
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]]
Yes, we can find the index of an element in a vector as follows:是的,我们可以找到向量中元素的索引,如下所示:
> a <- c(3, 2, -7, -3, 5, 2)
> b <- (a==-7) # this will output a TRUE/FALSE vector
> c <- which(a==-7) # this will give you numerical value
> a
[1] 3 2 -7 -3 5 2
> b
[1] FALSE FALSE TRUE FALSE FALSE FALSE
> c
[1] 3
This is one of the most efficient methods of finding the index of an element in a vector.这是在向量中查找元素索引的最有效方法之一。
R has overloaded the double equals ==
operator with a method of finding the index of a needle in a vector haystack. R用一种在向量干草堆中查找针的索引的方法使double equals
==
运算符超载。 It yields a logical
vector, containing TRUE
values for each match in the haystack. 它产生一个
logical
向量,其中包含TRUE
中每个匹配项的TRUE
值。
Example: 例:
haystack <- c(1, 2, 4, 3, 4)
needle <- 4
indices <- needle == haystack
indices
[1] 3 5
haystack[indices]
[1] 4 4
It works if both are vectors, and can be expanded to use multiple vectors as well. 如果两者都是向量,则可以使用,也可以扩展为使用多个向量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.