[英]speed up a monte carlo simulation with nested loop in R
I would like to speed up the below monte carlo simulation of a DEA estimate 我想加快以下DEA估算的蒙特卡洛模拟
A<-nrow(banks)
effm<-matrix(nrow=A, ncol=2)
m<-20
B<-100
pb <- txtProgressBar(min = 0,
max = A, style=3)
for(a in 1:A) {
x1<-x[-a,]
y1<-y[-a,]
theta=matrix(nrow=B,ncol=1)
for(i in 1:B){
xrefm<-x1[sample(1:nrow(x1),m,replace=TRUE),]
yrefm<-y1[sample(1:nrow(y1),m,replace=TRUE),]
theta[i,]<-dea(matrix(x[a,],ncol=3),
matrix(y[a,],ncol=3),
RTS='vrs',ORIENTATION='graph',
xrefm,yrefm,FAST=TRUE)
}
effm[a,1]=mean(theta)
effm[a,2]=apply(theta,2,sd)/sqrt(B)
setTxtProgressBar(pb, a)
}
close(pb)
effm
Once A becomes large the simulation freezes. 一旦A变大,模拟将冻结。 i am aware from online research that the apply function rapidly speeds up such code but am not sure how to use it in the above procedure. 我从在线研究中了解到apply函数可以迅速加快此类代码的速度,但不确定如何在上述过程中使用它。
Any help/direction would be much appreciated 任何帮助/方向将不胜感激
Barry 巴里
The following should be faster.... but if you're locking up when A is large that might be a memory issue and the following is more memory intensive. 以下操作应该会更快。...但是如果在A较大时锁定,则可能是内存问题,而以下操作会占用更多的内存。 More information, like what banks
is, what x
is, y
, where you get dea
from, and what the purpose is would be helpful. 更多信息,例如什么是banks
,什么是x
, y
,从何处获得dea
以及目的是什么都会有所帮助。
Essentially all I've done is try to move as much as I can out of the inner loop. 从本质上讲,我所做的就是尝试尽我所能地移出内循环。 The shorter that is, the better off you'll be. 越短,您的生活就越好。
A <- nrow(banks)
effm <- matrix(nrow = A, ncol = 2)
m <- 20
B <- 100
pb <- txtProgressBar(min = 0,
max = A, style=3)
for(a in 1:A) {
x1 <- x[-a,]
y1 <- y[-a,]
theta <- numeric(B)
xrefm <- x1[sample(1:nrow(x1), m * B, replace=TRUE),] # get all of your samples at once
yrefm <- y1[sample(1:nrow(y1), m * B, replace=TRUE),]
deaX <- matrix(x[a,], ncol=3)
deaY <- matrix(y[a,], ncol=3)
for(i in 1:B){
theta[i] <- dea(deaX, deaY, RTS = 'vrs', ORIENTATION = 'graph',
xrefm[(1:m) + (i-1) * m,], yrefm[(1:m) + (i-1) * m,], FAST=TRUE)
}
effm[a,1] <- mean(theta)
effm[a,2] <- sd(theta) / sqrt(B)
setTxtProgressBar(pb, a)
}
close(pb)
effm
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.