问题描述
#为什么这段代码在 R 中需要很长时间?
k<-1000
dat <- NULL
for (x in 0:k){
for (j in 0:k){
Y <- ((x + j)/2)
dat <- rbind(dat,x,j,Y)
}
}
out <- list(dat=dat)
解决方法
这是一些方法的基准。我已将问题中的代码修改为我认为您想要的。您可能希望对其他一些 k 值重复此操作。
library(microbenchmark)
k <- 2
microbenchmark(
ques = {
res_q <- NULL
for (x in 0:k){
for (j in 0:k){
Y <- ((x + j)/2)
res_q <- rbind(res_q,c(x,j,Y))
}
}
res_q
},expand.grid = {
g <- expand.grid(x = 0:k,j = 0:k)[2:1]
res_g <- as.matrix(transform(g,Y = (x + j) / 2))
dimnames(res_g) <- NULL
res_g
},rep = {
res_r <- cbind(x = rep(x = 0:k,each = k+1),j = 0:k,Y = NA)
res_r[,"Y"] <- rowSums(res_r[,1:2]) / 2
dimnames(res_r) <- NULL
res_r
})
## Unit: microseconds
## expr min lq mean median uq max neval cld
## ques 28829.2 29268.00 30493.273 29712.45 30303.5 56836.1 100 c
## expand.grid 1719.3 1784.85 1892.908 1882.70 1917.1 3706.7 100 b
## rep 70.3 81.55 114.655 118.00 137.9 212.6 100 a
我们验证所有方法都给出了相同的结果:
all.equal(res_q,res_g,res_r)
## [1] TRUE