即使没有导出变量和指定包依赖关系,foreach也可以工作 [英] foreach works even without exporting variable and specifying package dependency
问题描述
foreach
要求我指定:
.packages包含任务依赖的包的字符向量。
。导出要导出的变量的字符向量。当访问一个未在当前
环境中定义的变量时,这可能是
。
然而, ,即使我的每个任务都依赖于 library(tree)
和变量公式
,下面的代码也能正常工作。为什么我不需要指定 .packages =tree,.export =公式
?
<$ p数据库(树)
数据(虹膜)
registerDoMC(2)
公式< - c(as.formula(Species〜 (I =(1:2))%),
as.formula(Species〜Petal.Length + Petal.Width))
Res< - foreach (公式,数据=虹膜)
}
/ pre>
doMC后端使用mclapply函数,mclapply派生其工作人员,所以工作人员从当前进程继承他们的环境。因此,您不必使用 .packages
选项来加载已加载的包,或使用 .export
选项来导出在当前环境中定义的变量。 doSNOW,doMPI和doRedis等后端不使用fork,因此与doMC一起工作的foreach循环可能无法在这些后端上工作。
我认为这是一个很好的做法使用这些选项与doMC,因为它使代码更便携,但正如你发现,并不总是必要的。
Reading the doc and SO questions, it seems that foreach
requires me to specify:
.packages character vector of packages that the tasks depend on.
.export character vector of variables to export. This can be useful when accessing a variable that isn't defined in the current environment.
However, the following code works even though each of my task depends on library(tree)
and variable formulas
. Why don't I have to 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)
}
The doMC backend uses the mclapply function and mclapply forks its workers, so the workers inherit their environment from the current process. Therefore you don't have to use the .packages
option to load packages that are already loaded or use the .export
option to export variables that are defined in the current environment. Backends such as doSNOW, doMPI and doRedis don't use fork, so foreach loops that work with doMC may not work on these backends.
I think it's a good practice to use those options with doMC because it makes the code more portable, but as you've discovered, it isn't always necessary.
这篇关于即使没有导出变量和指定包依赖关系,foreach也可以工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!