R
Beginner
1 min read
Linear Regression with lm()
Example
data(mtcars)
# Simple linear regression: mpg ~ wt
model1 <- lm(mpg ~ wt, data = mtcars)
summary(model1)
# Coefficients:
# Estimate Std. Error t value Pr(>|t|)
# (Intercept) 37.285 1.878 19.858 < 2e-16 ***
# wt -5.344 0.559 -9.559 1.29e-10 ***
coef(model1) # intercept and slope
confint(model1) # 95% CI for each coefficient
residuals(model1)[1:5]
fitted(model1)[1:5]
# Multiple linear regression
model2 <- lm(mpg ~ wt + hp + cyl, data = mtcars)
summary(model2)
# Model with interaction
model3 <- lm(mpg ~ wt * cyl, data = mtcars)
# equivalent to: mpg ~ wt + cyl + wt:cyl
summary(model3)
# Polynomial term
model4 <- lm(mpg ~ wt + I(wt^2), data = mtcars)
summary(model4)
# Predict for new data
new_cars <- data.frame(wt = c(2.5, 3.0, 3.5),
hp = c(110, 130, 150),
cyl = c(4, 6, 8))
predict(model2, newdata = new_cars)
predict(model2, newdata = new_cars, interval = "confidence")
# ANOVA table for the model
anova(model2)
# Compare nested models
anova(model1, model2) # F-test for added predictors
# Diagnostic plots (opens 4 plots)
# par(mfrow = c(2, 2))
# plot(model1)
# R-squared and F-statistic
s <- summary(model1)
s$r.squared # 0.7528
s$adj.r.squared # 0.7446
s$fstatistic # F-value and df