Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to switch programmatically between %do% and %dopar% in foreach?

By changing %dopar% to %do% when using foreach, I can run the code sequentially. How can I do this programmatically?

E.g. I want the following but with only ONE foreach statement:

library(doParallel)
library(foreach)

registerDoParallel(cores = 4)

runner <- function(parallel = FALSE) {
  if (parallel)
    foreach(i=1:10) %dopar% {
      print(i)
    }
   else
    foreach(i=1:10) %do% {
      print(i)
    }
}

runner()
runner(TRUE)
like image 412
katsumi Avatar asked May 02 '17 08:05

katsumi


1 Answers

You could use ifelse to choose the infix function:

runner <- function(parallel = FALSE) {
     `%myinfix%` <- ifelse(parallel, `%dopar%`, `%do%`)
     foreach(i=1:10) %myinfix% {
         print(i)
     } 
}
like image 194
user1981275 Avatar answered Sep 19 '22 23:09

user1981275