R : catching errors in `nls`
Asked Answered
V

1

6

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

Verticillate answered 3/6, 2010 at 6:26 Comment(0)
A
12

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

}
Acantho answered 3/6, 2010 at 8:27 Comment(4)
Great! That's exactly what I needed! I just added a silent="TRUE" parameter to try, so I don't get errors printed out.Verticillate
@Acantho The logic of your answer makes sense. It is useful to know about the try command but I was expecting a nls call on line four of your post and am unfamiliar with the nul function that appears there. A quick search here hasn't helped me find out what nul does. Have you any hints on where to find out more on this? Maybe I don't know which package I should require?Favoritism
@JasonWhyte That's just a typo. I meant try(fit <- nls(...)) and fit will be NULL when nls induces an error.Acantho
@Acantho Thanks for the clarification. I was clutching at straws because using the solution above with nls (instead of nul) still didn't help me in all cases as the nls fitting seemed stuck in a loop. I've since worked out that I'm dealing with a completely different type of nls bug, one that doesn't return an error. I'll document this soon.Favoritism

© 2022 - 2024 — McMap. All rights reserved.