【问题标题】:tryCatch with a complicated function and plyr in R具有复杂功能的tryCatch和R中的plyr
【发布时间】:2013-02-11 01:51:24
【问题描述】:

我有一个复杂而冗长的函数,我用它来进行模拟。它可能会产生错误,主要与以零方差相等的值结束的随机向量有关,被输入 PCA 或逻辑回归。

我正在使用doMCplyr 在集群上执行它。我不想tryCatch函数内部的每一件小事,因为出错的可能性很多,而且每个错误的概率都很小。

我如何尝试每次运行,而不是 tryCatching 每一行?代码是这样的:

iteration = function(){
    a really long simulation function where errors can happen
    }
reps = 10000
results = llply(1:reps, function(idx){out<-iteration()},.parallel=TRUE)

大约一年后编辑: foreach 包比plyr 更容易做到这一点

library(foreach)
output <- foreach(i=1:reps, .errorhandling = 'remove')%dopar%{
  function
}

【问题讨论】:

    标签: r error-handling parallel-processing try-catch domc


    【解决方案1】:

    您可以在函数迭代中输入tryCatch,例如:

    iteration <- function(idx){
      tryCatch(
        { idx <- idx+1
          ## very long treatments here...
          ## I add a dummy error here to test my tryCatch
          if(idx %% 2000 ==0) stop("too many iterations")
        },error = function(e) print(paste('error',idx)))
    }
    

    现在在llply 内测试它,

    library(plyr)
    reps = 10000
    results = llply(1:reps, iteration,.parallel=TRUE)
    1] "error 2000"
    [1] "error 4000"
    [1] "error 6000"
    [1] "error 8000"
    [1] "error 10000"
    

    【讨论】:

      【解决方案2】:

      你能在传递给 llply 的函数中包装 try catch 循环吗?

      results = llply(1:reps, function(idx){
          out = NA
          try({ 
              out<-iteration()
          }, silent=T)
          out
      },.parallel=TRUE)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-06-20
        • 1970-01-01
        • 1970-01-01
        • 2018-02-01
        • 1970-01-01
        • 2018-03-22
        • 2020-11-07
        相关资源
        最近更新 更多