Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to export many variables and functions from global environment to foreach loop?

How can I export the global environment for the beginning of each parallel simulation in foreach? The following code is part of a function that is called to run the simulations.

  num.cores <- detectCores()-1
  cluztrr <- makeCluster(num.cores)
  registerDoParallel(cl = cluztrr)

  sim.result.list <- foreach(r = 1:simulations, 
      .combine = list,
      .multicombine = TRUE, 
      ) %dopar% {

          #...tons of calculations using many variables...

          list(vals1,
               vals2,
               vals3)
  }
 stopCluster(cluztrr)

Is it necessary to use .export with a character vector of every variable and function that I use? Would that be slow in execution time?

like image 281
Actuary_Greg Avatar asked Aug 19 '17 03:08

Actuary_Greg


1 Answers

If the foreach loop is in the global environment, variables should be exported automatically. If not, you can use .export = ls(globalenv()) (or .GlobalEnv).

For functions from other packages, you just need to use the syntax package::function.

like image 149
F. Privé Avatar answered Oct 18 '22 10:10

F. Privé