How to programmatically switch 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?

eg. I want the following, but only with ONE foreach:

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)

      

+3


source to share


1 answer


You can use ifelse

to select infix function:



runner <- function(parallel = FALSE) {
     `%myinfix%` <- ifelse(parallel, `%dopar%`, `%do%`)
     foreach(i=1:10) %myinfix% {
         print(i)
     } 
}

      

+4


source







All Articles