foreach icon indicating copy to clipboard operation
foreach copied to clipboard

Formula defined outside %dopar% cannot get variables in Global environment

Open PierreMasselot opened this issue 3 years ago • 0 comments

Hi,

I ran into an error while performing analyses in parallel, with a formula defined before the %dopar% loop that needs to get variables in the global environment. The following code throws an error:

x <- rnorm(100)
y <- 5 + 2 * x + rnorm(100, 0, .2)
form <- y ~ x

cl <- makeCluster(2)
registerDoParallel(cl)
foreach(i = 1:2, .packages = "mixmeta") %dopar% {
  model <- lm(form)
}
stopCluster(cl)

On the other hand, either putting the variables into a data.frame or defining the formula within the %dopar% loop work fine.

x <- rnorm(100)
y <- 5 + 2 * x + rnorm(100, 0, .2)
df <- data.frame(y = y, x = x)
form <- y ~ x

cl <- makeCluster(2)
registerDoParallel(cl)
foreach(i = 1:2) %dopar% {
  model <- lm(form, data = df)
}
stopCluster(cl)
x <- rnorm(100)
y <- 5 + 2 * x + rnorm(100, 0, .2)

cl <- makeCluster(2)
registerDoParallel(cl)
foreach(i = 1:2) %dopar% {
  model <- lm(y ~ x)
}
stopCluster(cl)

This is not a crippling issue as it is easy to find a workaround, but I thought you might want to know.

Thanks!

PierreMasselot avatar Aug 15 '22 16:08 PierreMasselot