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)
katsumi
  • 154
  • 8
  • 1
    If you have lots of code in place of `print(i)`, then maybe convert it to a function, or use `source`. – zx8754 May 02 '17 at 08:30
  • 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. – katsumi May 02 '17 at 08:35
  • It was a simple suggestion, a workaround. Trying to understand the motivation to make it programmatical. – zx8754 May 02 '17 at 08:52
  • 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. – katsumi May 02 '17 at 08:58
  • Also see `match.fun`. – zx8754 May 02 '17 at 09:26

1 Answers1

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)
     } 
}
user1981275
  • 13,002
  • 8
  • 72
  • 101
  • that seems to be too easy to be true - but really good to know. That might come handy in other scenarios as well! – katsumi May 02 '17 at 09:16