Fitting a polynomial regression model with lm
Some predictor variables and response variables may have a non-linear relationship, and their relationship can be modeled as an nth order polynomial. In this recipe, we will introduce how to deal with polynomial regression using the lm
and poly
functions.
Getting ready
Prepare the dataset that includes a relationship between the predictor and response variable that can be modeled as an nth order polynomial. In this recipe, we will continue to use the Quartet
dataset from the car
package.
How to do it...
Perform the following steps to fit the polynomial regression model with lm
:
- First, we make a scatter plot of the
x
andy2
variables:
> plot(Quartet$x, Quartet$y2)
Scatter plot of variables x and y2
- You can apply the
poly
function by specifying2
in the argument:
> lmfit = lm(Quartet$y2~poly(Quartet$x,2)) > lines(sort(Quartet$x), lmfit$fit[order(Quartet$x)], col = "red")
A quardratic fit example of the regression plot...