Assignment inside a parallel foreach loop

I am trying to start a large parallel operation, but, to my chagrin, I realized that I could not assign assignments in a parallel loop foreach. That is, an attempt to execute the following code will not change top

p <- numeric(3)
foreach(i=1:3) %dopar% {
  p[i] <- 1
}
p
# [1] 0 0 0

I thought this might be an environmental issue (i.e. the destination pis local), but changing <-to <<-only gave me an error:Error in { : task 1 failed - "object 'p' not found"

Is there any way to get remapping work or solve this problem?

In my real case p[i] <- 1, it is actually a redirect of many elements at once, randomly (but predefined before the loop) is placed in a vector, so using something like .combine = c, unfortunately, leaves the question.

What I have tried so far:

, .combine = `+`, :

s <- foreach(i=1:3, .combine = `+`) %dopar% {
  p <- numeric(3)
  p[i] <- 1
  p
}

, , ( , 6 , ), R 6.1 GB. , , , , , , , - , .

k-fold, , 1 - K, foreach - k = 1:K, folds != k, (folds == k). , , , -

folds <- sample(1:K, nrow(mydata), replace = TRUE)
preds <- numeric(nrow(mydata))
foreach(k=1:K) %do% {
  m <- fit_model(...)                    # Pseudocode
  preds[folds == k] <- predict_on_model(...) # Pseudocode
}

, - foreach .

+4
1

, , , foreach. , "", . :

library(doSNOW)
cl <- makeSOCKcluster(4)
registerDoSNOW(cl)
K <- 10
N <- 100
set.seed(4325)
folds <- sample(1:K, N, replace=TRUE)

comb <- function(p, ...) {
  for (r in list(...)) {
    p[folds == r$k] <- r$p
  }
  p
}

preds <-
  foreach(k=1:K, .combine='comb', .init=numeric(N),
          .multicombine=TRUE) %dopar% {
    p <- 100 + k  # replace this
    list(k=k, p=p)  # include data needed by the combine function
  }

foreach , "" . foreach .init, preds. , .

"" , folds:

reorder <- function(p) p[folds]
preds <-
  foreach(k=1:K, .combine='c', .final=reorder) %dopar% {
    100 + k  # replace this
  }

, , .

+4

All Articles