在R中设置临时变量会使效率变低
test <- rnorm(10)
names(test) <- letters[1:10]
A <- for (i in 1:10000) {
tmp <- test[order(test, decreasing = TRUE)]
res <- c(head(tmp, 2), tail(tmp, 2))
return(res)
}
B <- for (i in 1:10000) {
res <- c(head(test[order(test, decreasing = TRUE)], 2), tail(test[order(test, decreasing = TRUE)], 2))
return(res)
}
library(microbenchmark)
microbenchmark(A, B)
上述代码的运行结果为:
Unit: nanoseconds
expr min lq mean median uq max neval
A 29 31 46.14 31 32 1370 100
B 27 29 33.97 29 31 441 100