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?
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.
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.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With