Foreach works even without exporting a variable and defining a package dependency

Reading the doc and SO questions, it seems that foreach requires me to specify:

.packages is the character vector of packages on which tasks depend.

.export character vector of variables for export. This can be useful when accessing a variable that is not defined in the current environment.

However, the following code works, although each of my tasks depends on the library(tree) and the formulas variable. Why shouldn't I specify .packages="tree", .export="formulas" ?

 library(tree) data(iris) registerDoMC(2) formulas <- c(as.formula("Species ~ Sepal.Length + Sepal.Width"), as.formula("Species ~ Petal.Length + Petal.Width")) Res <- foreach(i=(1:2)) %dopar% { formula <- formulas[[i]] grown_tree <- tree(formula, data=iris) } 
+2
source share
1 answer

The doMC backend uses the mclapply function and mclapply deploys its workers, so workers inherit their environment from the current process. Therefore, you do not need to use the .packages parameter to load already downloaded packages or use the .export parameter to export variables that are defined in the current environment. Backends such as doSNOW, doMPI, and doRedis do not use fork, so the foreach loops that work with doMC may not work on these backends.

I find it good practice to use these options with doMC because it makes the code more portable, but as you discovered, this is not always necessary.

+2
source

All Articles