假设我们有vector(或者data.frame就此而言)如下:
set.seed(1)
x <- sample(10, 1e6, TRUE)
Run Code Online (Sandbox Code Playgroud)
而一个人想获得的所有值都x在那里x > 4,说:
a1 <- x[x > 4] # (or)
a2 <- x[which(x > 4)]
identical(a1, a2) # TRUE
Run Code Online (Sandbox Code Playgroud)
我想大多数人都会喜欢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
Run Code Online (Sandbox Code Playgroud)
它比我快2.1倍.
我认为,差异的一种可能性可能是由于 …