Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fitting polynomial model to data in R

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

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?

like image 650
Mehper C. Palavuzlar Avatar asked Sep 29 '10 14:09

Mehper C. Palavuzlar


People also ask

How do you fit a polynomial into data points?

To perfectly fit a polynomial to data points, an order polynomial is required. To restate slightly differently, any set of points can be modeled by a polynomial of order . It can be shown that such a polynomial exists and that there is only one polynomial that exactly fits those points.

Does polynomial regression fits a curve line to your data?

The most common way to fit curves to the data using linear regression is to include polynomial terms, such as squared or cubed predictors. Typically, you choose the model order by the number of bends you need in your line.

How do I fit a curve to data in R?

To fit a curve to some data frame in the R Language we first visualize the data with the help of a basic scatter plot. In the R language, we can create a basic scatter plot by using the plot() function. where, df: determines the data frame to be used.


1 Answers

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).

like image 146
Greg Avatar answered Sep 18 '22 10:09

Greg