Tell me more ×
Cross Validated is a question and answer site for statisticians, data analysts, data miners and data visualization experts. It's 100% free, no registration required.

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

share|improve this question
3  
What are the messages? I would guess they are related to the nondifferentiability of the first model and the terrible starting values in the second. – whuber Jun 5 '11 at 22:05
For first model the error message is Error in nlsModel(formula, mf, start, wts) : singular gradient matrix at initial parameter estimates; For the second model the Error message is: 133504.8 : 4250.0 10.0 0.1 Error in nls(formula = y ~ K * a * exp(-(a/b) * exp(-b * x) - b * x), : singular gradient – MYaseen208 Jun 5 '11 at 22:12
1  
For the first problem, use an optimizer that does not assume differentiability. (There's a list of optimizers at cran.r-project.org/web/views/Optimization.html .) For the second, start with a better estimate. – whuber Jun 5 '11 at 22:22

1 Answer

up vote 4 down vote accepted

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).

share|improve this answer
Thanks a lot. Both models worked. Thanks again for your help. – MYaseen208 Jun 5 '11 at 22:45

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.