我正在使用此伪数据尝试对其进行并行化,到目前为止,我还无法获得与非并行化代码相同的结果。
虚拟矩阵:
m <- matrix(1, nrow = 500, ncol = 500)
m[1,1] <- 2 # To check the output keeps rows and columns in same order
m[2,2] <- 2
m[103,203] <- 2
这按预期工作:
for (i in 1:dim(m)[1]){
for (j in 1:dim(m)[2]){
m[i,j] <- m[i,j] + 1
}
}
此不按预期方式工作:
cl <- makeCluster(4, type = "SOCK")
registerDoParallel(cl)
output <- foreach(i=1:dim(m)[1]) %dopar% {
df <- data.frame()
for( j in 1:dim(m)[2]){
df[i,j] <- m[i,j] + 1
}
df
}
stopCluster(cl)
这都不是
cl <- makeCluster(4, type = "SOCK")
registerDoParallel(cl)
output <- foreach(i=1:dim(m)[1],.combine='cbind' ) %:%
foreach (j=1:dim(m)[2], .combine='c') %do% {
m[i,j] <- m[i,j] + 1
}
stopCluster(cl)