2
votes

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

3

3 Answers

7
votes

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  
6
votes

For completeness, you can include Senor O solution within ggplot2 framework to get a plot of the smoothed solution and check the solution graphically:

library(ggplot2)
ggplot(dat,aes(x=xdata,y=ydata)) +
   geom_point() +
   geom_smooth(method="nls", formula=y ~ p1+p2*x^2, se=FALSE, 
               start=list(p1=p1,p2=p2))

enter image description here

4
votes

You have no parameters in your formula. You need to include them however you see fit:

nls(ydata ~ p1 * xdata^2 + p2, start=list(p1=p1,p2=p2))