我正在使用nls
拟合一些指数数据。
我正在使用的代码是:
fit <- nls(y ~ expFit(times, A, tau, C), start = c(A=100, tau=-3, C=0))
expFit
定义为
expFit <- function(t, A, tau, C)
{
expFit <- A*(exp(-t/tau))+C
}
这适用于我的大多数数据,其中提供的起始参数(100,-3和0)运行良好。但有时,我的数据与这些参数不相符,我从nls
得到错误(例如“奇异渐变”或类似的东西)。我如何“捕获”这些错误?
我尝试做类似
的事情fit <- NULL
fit <- nls(...)
if (is.null(fit))
{
// Try nls with other starting parameters
}
但这不起作用,因为nls
似乎停止了执行,而nls
之后的代码将无法执行......
有什么想法吗?
由于 尼科
答案 0 :(得分:10)
我通常使用这个技巧:
params<-... # setup default params.
while(TRUE){
fit<-NULL
try(fit<-nls(...)); # does not stop in the case of error
if(!is.null(fit))break; # if nls works, then quit from the loop
params<-... # change the params for nls
}