[R] fitting a quadratic function - poly?

Duncan Murdoch murdoch at stats.uwo.ca
Wed Apr 14 17:33:37 CEST 2010


On 14/04/2010 11:12 AM, Stefan Uhmann wrote:
> Hi List,
>
> I can not get my head around the following problem. I want to fit a 
> quadratic function to some data and stumbled across poly(). What exactly 
> does it, i.e. why are there different results for fit1 and fit2?
>
> x = seq(-10, 10)
> y = x^2
>
> fit1 = lm(y ~ x + I(x^2))
> fit2 = lm(y ~ poly(x, 2))
>
> plot(x,y)
> lines(x, fit1$fitted.values, col = 2)
> lines(x, fit2$fitted.values, col = 3)
>   

These look the same to me.
> round(fit1$coefficients, 2)
> round(fit2$coefficients, 2)
>   

These look different, because poly uses orthogonal polynomials, a 
different parametrization.  You can see the difference if you ask for 
model.matrix(fit1) and model.matrix(fit2).  (You can plot these using 
matplot(model.matrix(fit1)), etc.)

Duncan Murdoch
> Thanks in advance,
> Stefan
>
> ______________________________________________
> 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.
>



More information about the R-help mailing list