我的测试并没有证实你的所有主张,但这似乎(?)是由于跨平台差异(这使得问题变得更加神秘,并且可能值得考虑)[email protected] /cdn-cgi/l/email-protection
,虽然也许不是因为fastmatch
无论如何,下面的解决方案占主导地位......)
n <- 10^3; Lim <- 10^5
set.seed(101)
samp1 <- sample(Lim,n)
set1 <- sample(Lim,Lim)
library("rbenchmark")
library("fastmatch")
`%fin%` <- function(x, table) {
stopifnot(require(fastmatch))
fmatch(x, table, nomatch = 0L) > 0L
}
benchmark(which=sapply(samp1,function(x) which(set1==x)),
infun=sapply(samp1,function(x) x %in% set1),
fin= sapply(samp1,function(x) x %fin% set1),
brc= sapply(samp1,BinVecCheck,vec=sort(set1)),
replications=20,
columns = c("test", "replications", "elapsed", "relative"))
## test replications elapsed relative
## 4 brc 20 0.871 2.329
## 3 fin 20 0.374 1.000
## 2 infun 20 6.480 17.326
## 1 which 20 10.634 28.433
这说的是%in%
大约是两倍which
- 你的BinVecCheck
功能好 7 倍,但fastmatch
解决方案来自here https://stackoverflow.com/questions/32934933/faster-in-operator得到另一个因子 2。我不知道专门的 Rcpp 实现是否可以做得更好......
事实上,即使运行您的代码,我也会得到不同的答案:
## user system elapsed (which)
## 0.488 0.096 0.586
## user system elapsed (%in%)
## 0.184 0.132 0.315
## user system elapsed (is.element)
## 0.188 0.124 0.313
## user system elapsed (match)
## 0.148 0.164 0.312
## user system elapsed (BinVecCheck)
## 0.048 0.008 0.055
update: on r-devel
Peter Dalgaard 通过指出 R 来解释平台差异(这是 R 版本差异,而不是操作系统差异)NEWS https://cran.r-project.org/doc/manuals/r-devel/NEWS.html entry:
match(x, table)
更快,有时快一个数量级,当x
长度为 1 并且 incomparables 没有改变,这要归功于 Haverty 的 PR#16491。
sessionInfo()
## R Under development (unstable) (2015-10-23 r69563)
## Platform: i686-pc-linux-gnu (32-bit)
## Running under: Ubuntu precise (12.04.5 LTS)