fastmatch包实现了更快的 match
版本对于重复匹配(例如在循环中):
set.seed(1)
library(fastmatch)
table <- 1L:100000L
x <- sample(table, 10000, replace=TRUE)
system.time(for(i in 1:100) a <- match(x, table))
system.time(for(i in 1:100) b <- fmatch(x, table))
identical(a, b)
%in%
是否有类似的实现?我可以用来加速重复查找吗?
最佳答案
看%in%
的定义:
R> `%in%`
function (x, table)
match(x, table, nomatch = 0L) > 0L
<bytecode: 0x1fab7a8>
<environment: namespace:base>
自己写很容易
%fin%
功能:`%fin%` <- function(x, table) {
stopifnot(require(fastmatch))
fmatch(x, table, nomatch = 0L) > 0L
}
system.time(for(i in 1:100) a <- x %in% table)
# user system elapsed
# 1.780 0.000 1.782
system.time(for(i in 1:100) b <- x %fin% table)
# user system elapsed
# 0.052 0.000 0.054
identical(a, b)
# [1] TRUE
关于r - 更快的 %in% 运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32934933/