[R] Getting out of an embedded function safely - use try?

Douglas Bates bates at stat.wisc.edu
Tue Aug 26 21:47:19 CEST 2003


"Andy Bunn" <abunn at montana.edu> writes:

> Helpers.
> 
> An instrument sends me data that is mostly nonlinear. I have a group of
> functions to manipulate this data so that it is useful to the user. One
> of them involves a nls model that called to fit a line to the data and
> returns the fits. This works well 99 out of 100 times. Occasionally, the
> sensor sends some bad data to which a nls model cannot be fit. When that
> happens, the nls function cannot resolve and quits. This breaks the loop
> and ends the processing.
> 
> The problem is that the nls model is the middle of three functions that
> gathers, detrends, and collates n observations before returning a mean
> value function of several data series.
> 
> I want to make this program robust to bad data. So, if a bad data series
> is encountered I want the nls model to return an NA (or something like
> that). Is that possible? 

Yes

> Should I use try() and change the error option? 

> Or incorporate an inherits() within an if statement?

Both.  Check the code in the formula method for the generic function
nlsList in the nlme package for an example

    val <- lapply(split(data, groups), function(dat, formula, 
        start, control, first = TRUE) {
        ans <- try({
            data <- as.data.frame(dat)
            if (is.null(start)) {
                nls(formula = formula, data = data, control = control)
            }
            else {
                nls(formula = formula, data = data, start = start, 
                  control = control)
            }
        })
        if (inherits(ans, "try-error")) 
            NULL
        else ans
    }, formula = model, start = start, control = controlvals)


-- 
Douglas Bates                            bates at stat.wisc.edu
Statistics Department                    608/262-2598
University of Wisconsin - Madison        http://www.stat.wisc.edu/~bates/




More information about the R-help mailing list