Below you can find a piece of code in R which I would like to convert to run as a parallel process using several CPU's. I tried using foreach
package, but didn't go far.. I could not find a good example how to make it work given the fact I have 3-level nested loop. Help would be extremely appreciated. Example of code below - I made a simple function so it can serve as an example:
celnum <- c(10,20,30)
t2 <- c(1,2,3)
allrepeat <- 10
samplefunction <- function(celnum,t2){
x <- rnorm(100,celnum,t2)
y = sample(x, 1)
z = sample(x,1)
result = y+z
result
}
Getting results conventional way:
z_grid <- matrix(, nrow = length(celnum), ncol = length(t2))
repetitions <- matrix(, nrow = allrepeat, ncol = 1)
set.seed=20
for(i in 1:length(celnum)){
for (j in 1:length(t2)){
for (k in 1:allrepeat) {
results <- samplefunction(celnum[i],t2[j])
repetitions[k] <- results
z_grid[i,j] <- mean(repetitions,na.rm=TRUE)
}
}
}
z_grid
Now trying to do the same using foreach:
set.seed=20
library(foreach)
library(doSNOW)
cl <- makeCluster(3, type = "SOCK")
registerDoSNOW(cl)
set.seed=20
output <- foreach(i=1:length(celnum),.combine='cbind' ) %:%
foreach (j=1:length(t2), .combine='c') %:%
foreach (k = 1:allrepeat) %do% {
mean(samplefunction(celnum[i],t2[j]) )
}
output
This doesn't work as I would like it to, as it is returning a matrix of 30x2 dimensions instead 3x3. My intention is to simulate the scenario for i and j combinations k times, and would like to get an average of these k simulations for each combination of i and j.