R: show error and warning messages in foreach %dopar%

柔情痞子 提交于 2019-12-01 04:41:18

I think the issue is around your errorhandling and a bit of a misunderstanding of dopar. First, think of dopar more like a function. It must return an object back to the user by default as a list (it gathers all the output from each worker and the foreach function gathers these and returns them to use, see 'output_list' below).

You can also set .errorhandling = 'pass', it will return the error back to the output object (note probably only works if .combine ='list'). Here is how .errorhandling works:

.errorhandling specifies how a task evaluation error should be handled. If the value is "stop", then execution will be stopped via the stop function if an error occurs. If the value is "remove", the result for that task will not be returned, or passed to the .combine function. If it is "pass", then the error object generated by task evaluation will be included with the rest of the results. It is assumed that the combine function (if specified) will be able to deal with the error object. The default value is "stop".

Here is an example of how to set up a tryCatch inside of a foreach. Note that errors are now stored in output_list.

output_list = foreach(i=1:3, .errorhandling='pass') %dopar% {
result <- tryCatch({
    object_that_doesnt_exist[i]}, 
     warning = function(war) {
         return('a warning')}, 
     error = function(err) {
         return('an error')}, 
     finally = {
         return('other things')
     }) # END tryCatch

  return(result)  # return your result to outputlist
}

output_list
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!