【问题标题】:not avoiding/skipping errors with try and tryCatch不使用 try 和 tryCatch 避免/跳过错误
【发布时间】:2015-03-12 03:55:33
【问题描述】:

我在for loop 中有一个nlsLM,因为我想尝试不同的start values 来适应我的数据。我已经知道一些start values 会生成这个errorsingular gradient matrix at initial parameter estimates,但我想跳过这个error 并继续使用loop,用下一个start values 拟合回归。我试图将所有for loop 放在trytryCatch 块中,设置silence=TRUE,但是当singular gradient matrix at initial parameter estimates error 出现时代码仍然停止。

有人可以帮我吗?

代码如下:

try({
    for (scp.loop in scp.matrix){
    for (fit.rate in 1:10){
         print(scp.loop)
         print(fit.rate)

         #fit model with nlsLM
         #blah, blah, blah
     }}
     },silent=FALSE)

【问题讨论】:

  • 你能包含你使用的代码吗?我们可以指出问题可能出在哪里。
  • 当然,@DominicComtois!现在你有了代码。我对 R 和编程很陌生,也许我的代码是“脏的”。如果您有提高性能并使其更清洁的想法,我将不胜感激。

标签: r for-loop error-handling try-catch nls


【解决方案1】:

要了解问题,您需要了解try() 的工作原理。具体来说,try 将运行提供其第一个参数的代码,直到代码自行完成或遇到错误。 try() 所做的 特殊 事情是,如果您的代码中有错误,它将捕获该错误(不运行其第一个参数中的其余代码)并(1)返回该错误和一个普通的 R 对象和 (2) 允许代码 after try() 语句运行。例如:

x <- try({
    a = 1  # this line runs
    stop('arbitrary error') # raise an explicit error
    b = 2  # this line does not run
})
print('hello world') # this line runs despite the error

请注意,在上面的代码中 x 是类 'try-error' 的对象,而在下面的 codex 中等于 2(块的最后一个值):

x <- try({
    a = 1  # this line runs
    b = 2  # this line runs too
})

获取返回可以让你通过inherits(x,'try-error')测试是否有错误。

这适用于您的原因是我很确定您只想包含 在try() statemetn 中的 for 循环中运行的块,如下所示:

for (scp.loop in scp.matrix)
    for (fit.rate in 1:10)
        try({ 
            print(scp.loop)
            print(fit.rate)

            blah, blah, blah, 

            else{coeff.poly.only.res<<-coef(polyfitted.total)}
        },silent=FALSE)

【讨论】:

  • 谢谢@Jthorpe!这是我读过的最好的解释。现在我了解了try 的工作原理。我已经采纳了你的建议,我的代码现在运行良好。
猜你喜欢
  • 2017-02-06
  • 2017-02-25
  • 2019-03-01
  • 1970-01-01
  • 2015-08-20
  • 1970-01-01
  • 2021-08-06
  • 2021-06-16
  • 1970-01-01
相关资源
最近更新 更多