Fitting polynomial model to data in R

Mehper C. Palavuzlar picture Mehper C. Palavuzlar · Sep 29, 2010 · Viewed 144.3k times · Source

I've read the answers to this question and they are quite helpful, but I need help particularly in R.

I have an example data set in R as follows:

x <- c(32,64,96,118,126,144,152.5,158)  
y <- c(99.5,104.8,108.5,100,86,64,35.3,15)

I want to fit a model to these data so that y = f(x). I want it to be a 3rd order polynomial model.

How can I do that in R?

Additionally, can R help me to find the best fitting model?

Answer

Greg picture Greg · Sep 29, 2010

To get a third order polynomial in x (x^3), you can do

lm(y ~ x + I(x^2) + I(x^3))

or

lm(y ~ poly(x, 3, raw=TRUE))

You could fit a 10th order polynomial and get a near-perfect fit, but should you?

EDIT: poly(x, 3) is probably a better choice (see @hadley below).