Why is nls (Nonlinear Least Squares) not working in R

681 views Asked by At

I am trying to run nls and get back known parameters using following code:

I create a data.frame:

xx = 1:100
yy = 0.5*xx^2
dd = data.frame(xx,yy)
str(dd)
'data.frame':   100 obs. of  2 variables:
 $ xx: int  1 2 3 4 5 6 7 8 9 10 ...
 $ yy: num  0.5 2 4.5 8 12.5 18 24.5 32 40.5 50 ...

head(dd)
  xx   yy
1  1  0.5
2  2  2.0
3  3  4.5
4  4  8.0
5  5 12.5
6  6 18.0

I run nls on the data:

> nls(yy ~ A*(xx^B), data=dd)
Error in nls(yy ~ A * xx^B, data = dd) : 
  number of iterations exceeded maximum of 50
In addition: Warning message:
In nls(yy ~ A * xx^B, data = dd) :
  No starting values specified for some parameters.
Initializing ‘A’, ‘B’ to '1.'.
Consider specifying 'start' or using a selfStart model

I try adding 'start' parameters:

> nls(yy ~ A*(xx^B), data=dd, start=c(A=0.1, B=0.1))
Error in numericDeriv(form[[3L]], names(ind), env) : 
  Missing value or an infinity produced when evaluating the model

Where is the error and why am I not getting the parameters A=0.5 and B=2?

1

There are 1 answers

0
MrFlick On BEST ANSWER

Read the ?nls help page. Specifically the Warning about using nls on artificial "zero-residual" data. Try

yy = 0.5*xx^2 + rnorm(length(xx))

to add some noise