Rya*_*son 290 indexing r vectorization match
在R中,我有一个元素x
和一个向量v
.我想找到一个元素的第一个索引v
,它等于x
.我知道这样做的一种方法是:which(x == v)[[1]]
,但这似乎效率过低.有更直接的方法吗?
对于奖励积分,是否有一个功能,如果x
是一个矢量?也就是说,它应该返回一个索引向量,指示x
in 的每个元素的位置v
.
Jor*_*eys 411
该函数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
Run Code Online (Sandbox Code Playgroud)
match
仅按您的要求返回匹配的第一次遭遇.它返回第一个参数中值的第二个参数中的位置.
对于多重匹配,%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
Run Code Online (Sandbox Code Playgroud)
%in%
只要第一个参数返回逻辑向量TRUE
,可以在第二个参数中找到if值,FALSE
否则返回.
小智 24
Position
funprog {base}中的函数也可以完成这项工作.它允许您传递任意函数,并返回第一个或最后一个匹配.
Position(f, x, right = FALSE, nomatch = NA_integer)
小智 14
是的,我们可以按如下方式找到向量中元素的索引:
> 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
Run Code Online (Sandbox Code Playgroud)
这是查找向量中元素索引的最有效方法之一。
关于上述方法效率的小说明:
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
Run Code Online (Sandbox Code Playgroud)
所以,最好的是
which("Feb" == month.abb)[[1]]
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
484124 次 |
最近记录: |