假设我们有一个vector(或data.frame就此而言的)如下:
set.seed(1)
x <- sample(10, 1e6, TRUE)
并且想要获得xwhere的所有值x > 4,例如:
a1 <- x[x > 4] # (or)
a2 <- x[which(x > 4)]
identical(a1, a2) # TRUE
我想大多数人会更喜欢x[x > 4]. 但令人惊讶的是(至少对我而言),子集使用which更快!
require(microbenchmark)
microbenchmark(x[x > 4], x[which(x > 4)], times = 100)
Unit: milliseconds
expr min lq median uq max neval
x[x > 4] 56.59467 57.70877 58.54111 59.94623 104.51472 100
x[which(x > 4)] 26.62217 27.64490 28.31413 29.97908 99.68973 100
我的速度大约快 2.1 倍。
which我认为,差异的一种可能性可能是由于不考虑NA但也>返回它们的事实。但是逻辑运算本身应该是造成这种差异的原因,事实并非如此(显然)。那是:
microbenchmark(x > 4, which(x > 4), times = 100)
Unit: milliseconds
expr min lq median uq max neval
x > 4 8.182576 10.06163 12.68847 14.64203 60.83536 100
which(x > 4) 18.579746 19.94923 21.43004 23.75860 64.20152 100
which在子集之前使用大约慢 1.7 倍。但which似乎在子集期间/期间急剧赶上。
似乎不可能使用我通常选择的武器debugonce(感谢@GavinSimpson)作为which调用.Internal(which(x)),而==调用.Primitive("==")。
因此,我的问题是,为什么[on numerictypewhich 比逻辑向量更快>?有任何想法吗?