Search code examples
rmatlabforeachparallel.foreach

fixing foreach and dopar loop in R


Following the previous posthere, I wrote a code in R, but it does not work.

What I want to do is to have multiple output of arrays with foreach.

In Matlab, what I want to do is as follows. I want to have arrays X and Y by parellel computing.

X=zeros(2,5,10);
Y=zeros(10,2);
parfor i=1:10;
 X(:,:,i) = randn(2,5);
 Y(i,:) = randn(1,2);
end

Based on the comments for the previous post, I wrote an R code as follows. But, this does not work. The problem seems to be around the definition of Z.

rm(list=ls())   # clear all variables
library(foreach)
library(doParallel)

X <- array(0, dim = c(2,5,10))
Y <- array(0, dim = c(10,2))
Z <- foreach(i=1:10, .combine = 'c') %dopar% {
  Y_i <- i*c(1,2)
  X_i <- matrix(rnorm(10),2,5)
  Y[ i , ]  <- Y_i
  X[ , , i] <- X_i
  Z <- list(Y, X)
   }

Any help would be much appreciated.


Solution

  • The given code is almost done. Inside the loop, it is about environment (see the excellent explanation: http://adv-r.had.co.nz/Environments.html). Thus, like a function, it needs to return Z (local env) to Z (global env).

    rm(list=ls())   # clear all variables
    library(foreach)
    library(doParallel)
    
    X <- array(0, dim = c(2,5,10))
    Y <- array(0, dim = c(10,2))    
    Z <- foreach(i=1:10, .combine = 'c') %dopar% {
      Y_i <- i*c(1,2)  
      X_i <- matrix(rnorm(10),2,5)
      Y[ i , ]  <- Y_i
      X[ , , i] <- X_i
      Z <- list(Y, X)  
      Z
    }