[R] Substituting the extracted coefficients into the formula, exctracted from the result of nls()

Primoz PETERLIN primozz.peterlin at gmail.com
Fri Oct 9 09:55:05 CEST 2009

Dear all,

Here I come with another stupid question.  Suppose I want to use nls()
to fit a series of data (here modelled by generated points), then plot
the points and the fitting curve. I figured out some way of doing it:

x <- runif(1:20, 0, 10)
y <- 0.1*x^2 - rep(3, length(x)) + rnorm(length(x), sd = 0.5)

yfit <- nls(y ~ a*x^2 + b*x + c,
            start = list(a = 1, b = 1, c = 1),
            trace = TRUE)

plot(x, y)
curve(coef(yfit)[1]*x^2 + coef(yfit)[2]*x + coef(yfit)[3], 0, 10,
      add = TRUE)

However, this code is rather fortranesque, and most likely there
exists a much more elegant way in R/S, something like abline() which
exists for straight lines. Since both the formula and the coefficients
are available as a result of nls() (here as formula(yfit) and
coef(yfit)), I thought there ought to be a way something along the
following lines:

f <- substitute(formula(yfit), as.list(coef(yfit)))
curve(f, ...)

However, this snippet of code doesn't work. Am I thinking into the
correct direction at all?

Thanks in advance.

All the best,

Primož Peterlin,   Inštitut za biofiziko, Med. fakulteta, Univerza v Ljubljani
Lipičeva 2, SI-1000 Ljubljana, Slovenija.        primoz.peterlin at mf.uni-lj.si
Tel +386-1-5437612, fax +386-1-4315127,  http://biofiz.mf.uni-lj.si/~peterlin/
F8021D69 OpenPGP fingerprint: CB 6F F1 EE D9 67 E0 2F  0B 59 AF 0D 79 56 19 0F

More information about the R-help mailing list