以下代码是我项目的核心,但是考虑到我的问题规模,目前它太慢了。是否有更有效的方法来实现相同的结果?
nbassets <- 80
nbrisksource <- 100
nbsimul <- 300000
set.seed(100)
#generate random number for each 100 source of risk in many simulations
random <- matrix(runif(nbsimul*nbrisksource)+0.9,nrow=nbsimul,ncol=nbrisksource)
# random vulnerability to each source of risk for each of 120 assets
EL_decomp <- matrix(runif(nbassets*nbrisksource),nrow=nbassets,ncol=nbrisksource)
#initiate matrix to store asset returns
asset_ret <- matrix(NA, nrow=nbsimul,ncol=nbassets)
ptm <- proc.time()
#loop through each asset
for (i in 1:nbassets){
#determine if the asset has been impacted by any source of risk, if yes return is -1, otherwise 0
asset_ret[,i] <- apply(matrix(EL_decomp[i,], nrow=nbsimul,ncol=nbrisksource,byrow=TRUE) < random,1,all)-1
}
print(proc.time() - ptm)
ptm <- proc.time()
apply
的性能提升也不到0.5秒。 - Arthurapply(matrix(EL_decomp[i,],nrow=nbsimul,ncol=nbrisksource,byrow=TRUE)
返回一个布尔数组,而all(mat_80_100[i,] < mat_100_300000)
只返回一个布尔值。 - Simon Wuyaapply(EL_decomp, 1, function(x) (colSums(x < t(random)) == nbrisksource) - 1L)
。如果你不介意把这个作为答案发出来,我会接受它。否则我会自己发布。再次感谢。 - Simon Wuya