Solved – Fitting conditional functions in nls

modelingnlsnonlinear regressionr

I'm trying to fit two equations with nls() function in R. The two functions are:

$f(x) = c_{1} \exp\left(-\left(\frac{x-\mu}{\sigma_{(x)}}\right)^2\right)$

where $\sigma_{(x)} = \sigma_{11}$ if $x \le \mu$ and $\sigma_{(x)} = \sigma_{12}$ if $x > \mu$

and

$f(x) = a K \exp\left(- \frac{a}{b} \exp\left(-b x\right) – bx\right)$

Below is my attempt with factitious data:

x <- seq(from = 17, to = 47, by = 5)
y <- c(26.2, 173.6, 233.9, 185.9, 115.4, 62.0, 21.7)
Data <- data.frame(y, x)
Fit1 <- nls(formula =  y ~ if (x <= Mu) Mean <- c1*exp(-((x-Mu)/Sigma11)^2) else Mean     <- c1*exp(-((x-Mu)/Sigma12)^2),
                 data = Data, start = list(c1 = 240, Mu = 25, Sigma11 = 5, Sigma12 = 14), trace = TRUE)



Fit2 <- nls(formula =  y~K*a*exp(-(a/b)*exp(-b*x)-b*x), data = Data,
                start = list(K=4250, a=10, b=0.1), trace = TRUE)

Both codes produce Error and Warning messages. Any help to figure out these problems will be highly appreciated. Thanks

Best Answer

In the first case, nls will not digest any ifs or other higher expressions... you may use ifelse, however this may make this function too complex to effectively fit it -- nls is not a magic wand.

In the second case, the standard algorithm dies on numerical error -- the usual approach in this case is to alter starting point or change the used method; for instance

Fit2<-nls(y~K*a*exp(-(a/b)*exp(-b*x)-b*x),Data,
 start=list(K=4250,a=10,b=0.1),trace=T,algorithm="port")

do converge (consult ?nls for a list of methods).