============================================================

Regression on Auto Data: Nonlinear Relationship Check

============================================================

Install and load required packages

if (!require(ISLR2)) install.packages(“ISLR2”) library(ISLR2)

Load the Auto dataset

data(Auto) head(Auto)

============================================================

STEP 1: Simple Linear Regression (mpg ~ horsepower)

============================================================

lm_fit <- lm(mpg ~ horsepower, data = Auto) summary(lm_fit)

============================================================

STEP 2: Residual vs. Fitted Plot for LINEAR model

============================================================

par(mfrow = c(1, 2)) # side-by-side plots

Plot 1: Linear model residuals

plot(lm_fit\(fitted.values, lm_fit\)residuals, main = “Linear Modelvs. Fitted”, xlab = “Fitted Values”, ylab = “Residuals”, pch = 20, col = “steelblue”) abline(h = 0, col = “red”, lwd = 2, lty = 2) lines(lowess(lm_fit\(fitted.values, lm_fit\)residuals), col = “orange”, lwd = 2)

============================================================

STEP 3: Polynomial (Nonlinear) Regression

============================================================

poly_fit <- lm(mpg ~ poly(horsepower, 2), data = Auto) summary(poly_fit)

Plot 2: Polynomial model residuals

plot(poly_fit\(fitted.values, poly_fit\)residuals, main = “Polynomial (Degree 2) Modelvs. Fitted”, xlab = “Fitted Values”, ylab = “Residuals”, pch = 20, col = “darkgreen”) abline(h = 0, col = “red”, lwd = 2, lty = 2) lines(lowess(poly_fit\(fitted.values, poly_fit\)residuals), col = “orange”, lwd = 2)

par(mfrow = c(1, 1)) # reset layout

============================================================

STEP 4: Use built-in diagnostic plots (optional extra)

============================================================

par(mfrow = c(1, 2)) plot(lm_fit, which = 1, main = “Linear: Residuals vs Fitted”) plot(poly_fit, which = 1, main = “Poly: Residuals vs Fitted”) par(mfrow = c(1, 1))

============================================================

STEP 5: Scatter plot showing the fits

============================================================

plot(Auto\(horsepower, Auto\)mpg, main = “MPG vs Horsepower with Regression Fits”, xlab = “Horsepower”, ylab = “MPG”, pch = 20, col = “gray60”)

Linear fit line

abline(lm_fit, col = “steelblue”, lwd = 2)

Polynomial fit curve

hp_range <- seq(min(Auto\(horsepower), max(Auto\)horsepower), length.out = 300) poly_pred <- predict(poly_fit, newdata = data.frame(horsepower = hp_range)) lines(hp_range, poly_pred, col = “darkgreen”, lwd = 2)

legend(“topright”, legend = c(“Linear Fit”, “Polynomial Fit (degree 2)”), col = c(“steelblue”, “darkgreen”), lwd = 2)