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)
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