%运算符的%更快

Zac*_*ach 23 r match

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)
Run Code Online (Sandbox Code Playgroud)

是否有类似的实现%in%可用于加速重复查找?

Jos*_*ich 29

看看定义%in%:

R> `%in%`
function (x, table) 
match(x, table, nomatch = 0L) > 0L
<bytecode: 0x1fab7a8>
<environment: namespace:base>
Run Code Online (Sandbox Code Playgroud)

编写自己的%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
Run Code Online (Sandbox Code Playgroud)