title: Converting nested for-loop to parallel in R
body: <p>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 <code>foreach</code> 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:</p>
  
  <pre><code>celnum &lt;- c(10,20,30)
  t2 &lt;- c(1,2,3)
  allrepeat &lt;- 10
  
  samplefunction &lt;- function(celnum,t2){
  
          x &lt;- rnorm(100,celnum,t2)
          y = sample(x, 1)
          z = sample(x,1)
  
          result = y+z
  
  
          result 
  }
  </code></pre>
  
  <p>Getting results conventional way: </p>
  
  <pre><code>z_grid &lt;- matrix(, nrow = length(celnum), ncol = length(t2))
  
  repetitions &lt;- 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 &lt;- samplefunction(celnum[i],t2[j]) 
                                  repetitions[k] &lt;- results
                                  z_grid[i,j] &lt;- mean(repetitions,na.rm=TRUE) 
                  }  
          }
  }
  
  z_grid
  </code></pre>
  
  <p>Now trying to do the same using foreach:</p>
  
  <pre><code>set.seed=20
  
  library(foreach)
  library(doSNOW)
  
  cl &lt;- makeCluster(3, type = "SOCK")
  registerDoSNOW(cl)
  
  set.seed=20
  output &lt;- 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
  </code></pre>
  
  <p>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. </p>