[R] Getting out of an embedded function safely - use try?
Andy Bunn
abunn at montana.edu
Tue Aug 26 20:53:45 CEST 2003
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?
Should I use try() and change the error option?
Or incorporate an inherits() within an if statement?
Should I screen the data to check to see if it's well behaved before
getting into nls?
Thanks for any tips, Andy
#example
foo.one <- (1 * exp(-0.07 * 1:100) + 0.5) + rnorm(100, 0, 0.05)
foo.two <- (1 * exp(-0.000000001 * 1:100) + 0.5) + rnorm(100, 0, 0.05)
try.to.fit <- function(aVector){
toy.model <- nls(aVector ~ FitA * exp(FitNegB * 1:length(aVector)) +
FitK,
start = list( FitA = 0.75, FitNegB = -0.02, FitK = 0.4),
control = nls.control(maxiter=1000, tol=1e-05,
minFactor=1/1024))
return(fitted.values(toy.model))
}
try.to.fit(foo.one)
try.to.fit(foo.two)
More information about the R-help
mailing list