When do I need to specify .export in foreach()?

I'm trying to understand what the .export argument is for in foreach(). I first thought that all variables that are not explicitly specified in the ... arguments of foreach() would need to be exported to be used inside the foreach loop, but that was not the case as this example code works even though y isn't exported.

library(foreach)
library(parallel)
library(doParallel)
library(tidyverse)

x = rnorm(10000) %>% split(ceiling(seq_along(.) / 1000))
y = rnorm(1000)

cl = makeCluster(4)
registerDoParallel(cl)

lmfits = foreach(x = x) %dopar% {
  lm(y ~ x)
}

stopCluster(cl)

So in what circumstance do I need to specify the .export argument?

From help(foreach)

.export : character vector of variables to export. This can be useful when accessing a variable that isn't defined in the current environment. The default value in NULL.

In the example, y is informed in the global environment.

1 Like

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.