Problems with try() inside foreach() in R

后端 未结 2 1361
不知归路
不知归路 2021-02-07 11:18

I am trying to use the try() function to deal with errors that are occurring in my parallelised for loop:

results <- foreach (i = 1:2, .errorhand         


        
2条回答
  •  醉梦人生
    2021-02-07 11:40

    If you want to use the "remove" or "pass" error handling in foreach, you don't need to catch the error yourself. Here are the results when setting the error handling to "remove":

    > foreach (i = 1:2, .errorhandling = 'remove') %dopar% {
    +     myfun(i)
    + }
    [[1]]
    [1] 1.314854
    

    Here are the results when using "pass":

    > foreach (i = 1:2, .errorhandling = 'pass') %dopar% {
    +     myfun(i)
    + }
    [[1]]
    [1] 0.7247509
    
    [[2]]
    
    

    By using try, the error is caught and then translated to a "try-error" object by the try function, hiding the error from foreach until the the clusterApplyLB function (which is used to implement the doParallel backend) notices the "try-error" object in the list of results and throws an error in the master process. I would call that a bug in doParallel.

    Note that the solution given by @LegalizeIt works because it returns a NULL rather than a "try-error" object, thus avoiding the bug in doParallel.

提交回复
热议问题