You can do this with foreach using the abind function. Here is an example of using the doParallel package as a parallel backend, which is quite portable:
library(doParallel) library(abind) cl <- makePSOCKcluster(3) registerDoParallel(cl) acomb <- function(...) abind(..., along=3) guad <- foreach(r=1:4, .combine='acomb', .multicombine=TRUE) %dopar% { x <- matrix(rnorm(16), 4)
In this case, the join function acomb is used, which uses the abind function from the abind package to combine the matrices created by the cluster workers into a three-dimensional array.
In this case, you can also combine the results with cbind , and then change the dim attribute to convert the resulting matrix into a three-dimensional array:
guad <- foreach(r=1:4, .combine='cbind') %dopar% { x <- matrix(rnorm(16), 4)
Using abind is useful because it can combine matrices and arrays in various ways. Also remember that resetting the dim attribute can lead to duplication of the matrix, which can be a problem for large arrays.
Note that itβs nice to close the cluster at the end of the script with stopCluster(cl) .
source share