not avoiding/skipping errors with try and tryCatch

二次信任 提交于 2019-12-08 04:36:12

问题


I have a nlsLM inside a for loop because I want to try different start values to fit my data. I already know that some start values generates this error: singular gradient matrix at initial parameter estimates, but I want to skip this error and continue with the loop, fitting the regression with the next start values. I tried to put all the for loop inside a try and a tryCatch block, setting silence=TRUE, but the code still stopping when the singular gradient matrix at initial parameter estimates error occurs.

Someone can help me with that?

Here is the code:

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)

回答1:


To understand the problem you need to understand how try() works. Specifically, try will run the code provided it's first argument until the code completes on it's own or until it encounters an error. The special thing that try() does is that if there is an error in your code it will catch that error (without running the remainder of the code within it's first argument) and (1) return that error and an ordinary R object and (2) allow code after the try() statement to run. For example:

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

Note that in the above code x is an object of class 'try-error', whereas in the following codex is equal to 2 (the last value of the block):

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

obtaining the return allows you to test whether there was an error via inherits(x,'try-error').

How this applies to you is that I'm pretty sure you just want to include the block that runs within the for loops in your try() statemetn as in:

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)


来源:https://stackoverflow.com/questions/29001596/not-avoiding-skipping-errors-with-try-and-trycatch

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!