Olivier Delrieu
Olivier Delrieu

Reputation: 772

R foreach %dopar% : export results to main R process

%dopar% forks the main R process into several independent sub-processes. Is there a way to make these sub-processes communicate with the main R process, so that data can be 'recovered' ?

require(foreach) 
require(doMC) 
registerDoMC() 
options(cores = 2 )

a <- c(0,0)
foreach(i = 1:2 ) %do% {
    a[i] <- i
}
print(a) # returns 1 2

a <- c(0,0)
foreach(i = 1:2 ) %dopar% {
    a[i] <- i
}
print(a) # returns 0 0

Thanks!

Upvotes: 4

Views: 1768

Answers (3)

Mayou
Mayou

Reputation: 8848

If you want your result to be a dataframe, you could do:

 library(data.table)
 result <- foreach(i = 1:2) %dopar% {
      i
 }
 result.df <- rbindlist(Map(as.data.frame, result))

Upvotes: 1

Olivier Delrieu
Olivier Delrieu

Reputation: 772

Thanks to Karl, I now understand the purpose of '.combine'

a <- foreach(i = 1:2 , .combine=c) %dopar% {
    return(i)
}
print(a) # returns 1 2

Upvotes: 0

Karl Forner
Karl Forner

Reputation: 4414

You should read the foreach documentation:

The foreach and %do%/%dopar% operators provide a looping construct that can be viewed as a hybrid of the standard for loop and lapply function. It looks similar to the for loop, and it evaluates an expression, rather than a function (as in lapply), but it's purpose is to return a value (a list, by default), rather than to cause side-effects.

Try this:
a <- foreach(i = 1:2 ) %dopar% {
  i
}
print(unlist(a))

Upvotes: 4

Related Questions