我在nlsLM
中有一个for loop
,因为我想尝试其他start values
以适合我的数据。我已经知道一些start values
会生成此error
:singular gradient matrix at initial parameter estimates
,但是我想跳过此error
并继续loop
,使回归与下一个start values
相适应。我试图将所有for loop
放入try
和tryCatch
块中,设置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/