Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nonlinear least squares curve fitting in R

I am new to R (first time using it). and I am following this tutorial http://www.walkingrandomly.com/?p=5254 to try to plot a curve and discover the function that best fits my data. So far I have tryed:

> xdata = c(1 ,5, 10, 20, 100)
> ydata = c(23.83333333, 210.3666667, 545.3666667, 1756.866667, 38595.7)
> plot(xdata,ydata)

So I get this:

enter image description here

Then I try:

> p1 = 1
> p2 = 0.2
> fit = nls(ydata ~ xdata^2, start=list(p1=p1,p2=p2))

And I get this error:

Error in nlsModel(formula, mf, start, wts) : 
  singular gradient matrix at initial parameter estimates

What am I doing wrong? Thanks

like image 816
fredcrs Avatar asked Dec 04 '25 13:12

fredcrs


1 Answers

The nls function does not automatically include coefficients for all of your parameters in the model. You must explicitly include them in the formula. I'm not exactly sure where you wanted p1 and p2 to be included in the model from your description

p1 <- 1
p2 <- 0.2
fit <- nls(ydata ~ p1+p2*xdata^2, start=list(p1=p1,p2=p2))
fit

# Nonlinear regression model
#   model: ydata ~ p1 + p2 * xdata^2
#    data: parent.frame()
#      p1      p2 
# 127.216   3.847 
#  residual sum-of-squares: 21037
# 
# Number of iterations to convergence: 1 
# Achieved convergence tolerance: 5.774e-08

but at least in this form this is still a linear model. You can get the same fit with

fit2 <- lm(ydata ~ I(xdata^2))
fit2

# Call:
# lm(formula = ydata ~ I(xdata^2))
# 
# Coefficients:
# (Intercept)   I(xdata^2)  
#     127.216        3.847  
like image 160
MrFlick Avatar answered Dec 07 '25 05:12

MrFlick