Created
August 3, 2020 18:35
-
-
Save odinuv/2c98c3da1c38205c42bdc192798e66cf to your computer and use it in GitHub Desktop.
DoParallel with Retry
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(doParallel) | |
cl <- makeCluster(detectCores()-1,outfile="") | |
registerDoSEQ() | |
registerDoParallel(cl) | |
data = data.frame( | |
first = c('a', 'b', 'c', 'd', 'e'), | |
second = c('aa', 'bb', 'cc', 'dd', 'ee'), | |
third = c('aaa', 'bbb', 'ccc', 'ddd', 'eee'), | |
fourth = c('aaaa', 'bbbb', 'cccc', 'dddd', 'eeee'), | |
stringsAsFactors = FALSE | |
) | |
.GlobalEnv$raiseDemoError <- TRUE | |
work <- function (value, id) | |
{ | |
if (raiseDemoError && ((value == 'b') || (value == 'cccc'))) { | |
stop('Booo') | |
} | |
paste0("work", value, id) | |
} | |
result <- foreach(id = colnames(data), .errorhandling='pass') %:% | |
foreach(value = data[[id]], .errorhandling='pass') %dopar% { | |
res <- tryCatch({c('success', work(value, id))}, | |
warning = function(war) { | |
return(c('error', 'a warning'))}, | |
error = function(err) { | |
c('error', paste0('an error', err))}) # END tryCatch | |
result <- c(value, id, res) | |
} | |
.GlobalEnv$raiseDemoError <- FALSE | |
result <- lapply(result, function (elm) { | |
lapply(elm, function (e) { | |
if (e[3] == 'error') { | |
print(paste0("recomputing ", e[1], e[2])) | |
work(e[1], e[2]) | |
} else { | |
e[4] | |
} | |
}) | |
}) | |
print(result) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment