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

Henrique Dallazuanna wwwhsd at gmail.com
Fri Oct 9 15:46:30 CEST 2009


If you want curve with substitute(...), you can try something about like this:

f <- eval(parse(text = paste("substitute(", formula(yfit)[3], ",
as.list(coef(yfit)))", sep = "")))
curve(f, ...)

2009/10/9 Henrique Dallazuanna <wwwhsd at gmail.com>:
> Try with predict:
>
> plot(x, y)
> lines(0:10, predict(yfit, list(x = 0:10)))
>
> 2009/10/9 Primoz PETERLIN <primozz.peterlin at gmail.com>:
>> 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ž
>>
>> --
>> 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
>>
>> ______________________________________________
>> R-help at r-project.org mailing list
>> https://stat.ethz.ch/mailman/listinfo/r-help
>> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
>> and provide commented, minimal, self-contained, reproducible code.
>>
>
>
>
> --
> Henrique Dallazuanna
> Curitiba-Paraná-Brasil
> 25° 25' 40" S 49° 16' 22" O
>



-- 
Henrique Dallazuanna
Curitiba-Paraná-Brasil
25° 25' 40" S 49° 16' 22" O




More information about the R-help mailing list