R(26), Nonlinear Least Square

Published: by Creative Commons Licence

Non-linear least squares: Determine the nonlinear (weighted) least-squares estimates of the parameters of a nonlinear model.

nls(formula, data, start)
  • formula: a nonlinear model formula including variables and parameters. Will be coerced to a formula if necessary.
  • data: an optional data frame in which to evaluate the variables in formula and weights. Can also be a list or an environment, but not a matrix.
  • start: a named list or named numeric vector of starting estimates. When start is missing (and formula is not a self-starting model, see selfStart), a very cheap guess for start is tried (if algorithm != "plinear").

example: In the example, we'll see what the confidence intervals for these assumptions are so that we can judge how good these values are in the model.

At first, we assume that the formula is like:

a = b1*x^2 + b2
xvalues <- c(1.6,2.1,2,2.23,3.71,3.25,3.4,3.86,1.19,2.21)
yvalues <- c(5.19,7.43,6.94,8.11,18.75,14.88,16.06,19.12,3.21,7.58)

# Give the chart file a name.
png(file = "nls.png")

# Plot these values.
plot(xvalues,yvalues)

# Take the assumed values and fit into the model.
model <- nls(yvalues ~ b1*xvalues^2+b2,start = list(b1 = 1,b2 = 3))

# Plot the chart with new data by fitting it to a prediction from 100 data points.
new.data <- data.frame(xvalues = seq(min(xvalues),max(xvalues),len = 100))
lines(new.data$xvalues,predict(model,newdata = new.data))

# Save the file.
dev.off()

# Get the sum of the squared residuals.
print(sum(resid(model)^2))

# Get the confidence intervals on the chosen values of the coefficients.
print(confint(model))

result:

[1] 1.081935
Waiting for profiling to be done...
       2.5%    97.5%
b1 1.137708 1.253135
b2 1.497364 2.496484