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

1

7

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)
Drobman answered 2/5, 2017 at 8:21 Comment(5)
If you have lots of code in place of print(i), then maybe convert it to a function, or use source.Impressment
That might be a smart move but I don't see how thats helping me with my question. The code was just a very non-realistic example.Drobman
It was a simple suggestion, a workaround. Trying to understand the motivation to make it programmatical.Impressment
For various reasons it could make sense to switch on the fly - sometimes just for debug reasons. I really dont want to edit the code every time though and neither do I want to introduce more or less redundant foreach statements.Drobman
Also see match.fun.Impressment
G
9

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)
     } 
}
Grevera answered 2/5, 2017 at 9:3 Comment(1)
that seems to be too easy to be true - but really good to know. That might come handy in other scenarios as well!Drobman

© 2022 - 2024 — McMap. All rights reserved.