try 和 tryCatch 没有 avoiding/skipping 错误

not avoiding/skipping errors with try and tryCatch

我在 for loop 中有一个 nlsLM,因为我想尝试不同的 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 将 运行 提供第一个参数的代码,直到代码自行完成或遇到错误。 special try() 所做的事情是,如果您的代码中有错误,它将捕获该错误(没有 运行ning 代码中的其余部分第一个参数)和(1)return那个错误和一个普通的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 是 class 'try-error' 的对象,而在以下代码中,x 等于 2(块的最后一个值):

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

获取return可以让你通过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)