r - 使用try和tryCatch无法避免/跳过错误

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

我在nlsLM中有一个for loop,因为我想尝试其他start values以适合我的数据。我已经知道一些start values会生成此error:singular 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)

最佳答案

要了解该问题,您需要了解try()的工作原理。具体来说,try将运行提供其第一个参数的代码,直到代码自行完成或遇到错误为止。 try()所做的特殊事情是,如果您的代码中有错误,它将捕获该错误(无需在其第一个参数中运行其余代码),并且(1)返回该错误和一个普通的R对象,以及(2)允许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”类的对象,而下面的代码x等于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)

关于r - 使用try和tryCatch无法避免/跳过错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29001596/

相关文章:

java - 用于打印合数的循环生成器

sql - R 中的 Copy_to 导致日期被转换为数字列

java - 在迭代循环中使用字节是否更有效?

javascript - 使用 for 循环检查两个数组中的匹配值,迭代较小的循环是否更快?

java - Firebase 休息 API 过滤器查询

ruby - Ruby错误- '+' : no implicit conversion of Fixnum into String (TypeError)

r - 绑定(bind)2个不同行数的数据集

r - 如何交叉引用 R 帮助文件/roxygen2 中的方程

r - 如何在多列之间进行偏相关分析并通过多个协变量进行控制?

r - R tryCatch跳过for循环中的错误,但未执行错误语句