install.packages("ISLR")
## Installing package into '/cloud/lib/x86_64-pc-linux-gnu-library/4.4'
## (as 'lib' is unspecified)
library(ISLR)
data("Auto") # Example dataset from ISLR package
# Install and load the ISLR package
install.packages("ISLR")
## Installing package into '/cloud/lib/x86_64-pc-linux-gnu-library/4.4'
## (as 'lib' is unspecified)
library(ISLR)
# Load the Auto dataset
data("Auto")
# Fit the linear model
lm_fit <- lm(mpg ~ horsepower, data = Auto)
# Print the summary of the linear model
summary(lm_fit)
##
## Call:
## lm(formula = mpg ~ horsepower, data = Auto)
##
## Residuals:
## Min 1Q Median 3Q Max
## -13.5710 -3.2592 -0.3435 2.7630 16.9240
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 39.935861 0.717499 55.66 <2e-16 ***
## horsepower -0.157845 0.006446 -24.49 <2e-16 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 4.906 on 390 degrees of freedom
## Multiple R-squared: 0.6059, Adjusted R-squared: 0.6049
## F-statistic: 599.7 on 1 and 390 DF, p-value: < 2.2e-16
# Create a new data frame with horsepower = 98
new_data <- data.frame(horsepower = 98)
# Predicted mpg with 95% confidence interval
predicted_values <- predict(lm_fit, new_data, interval = "confidence", level = 0.95)
predicted_values
## fit lwr upr
## 1 24.46708 23.97308 24.96108
# Predicted mpg with 95% prediction interval
predicted_values_with_prediction <- predict(lm_fit, new_data, interval = "prediction", level = 0.95)
predicted_values_with_prediction
## fit lwr upr
## 1 24.46708 14.8094 34.12476
# Plot mpg vs horsepower
plot(Auto$horsepower, Auto$mpg, main = "MPG vs Horsepower",
xlab = "Horsepower", ylab = "MPG", pch = 19, col = "blue")
# Add the regression line
abline(lm_fit, col = "red")

# Diagnostic plots
par(mfrow = c(2, 2)) # Arrange plots in a 2x2 grid
plot(lm_fit)
