R:在'nls`中捕捉错误

时间:2010-06-03 06:26:05

标签: r exception-handling curve-fitting nls

我正在使用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之后的代码将无法执行......

有什么想法吗?

由于 尼科

1 个答案:

答案 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

}