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 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)
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)
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.