R : catching errors in `nls`

喜夏-厌秋 提交于 2019-12-30 03:26:08

问题


I'm fitting some exponential data using nls.

The code I'm using is:

fit <- nls(y ~ expFit(times, A, tau, C), start = c(A=100, tau=-3, C=0))

expFit is defined as

expFit <- function(t, A, tau, C)
    {
    expFit <- A*(exp(-t/tau))+C
    }

This works well for most of my data, for which the starting parameters provided (100, -3 and 0) work well. Sometimes, though, I have data that doesn't go well with those parameters and I get errors from nls (e.g. "singular gradient" or things like that). How do I "catch" these errors?

I tried to do something like

fit <- NULL
fit <- nls(...)

if (is.null(fit))
    {
    // Try nls with other starting parameters
    }

But this won't work because nls seems to stop the execution and the code after nls will not execute...

Any ideas?

Thanks nico


回答1:


I usually use this trick:

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

}


来源:https://stackoverflow.com/questions/2963729/r-catching-errors-in-nls

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