01 / 21

Linear Models in R
lm()

Learn to fit, interpret, and diagnose simple linear regression using the lm() function: from \( y = \beta_0 + \beta_1 x + \varepsilon \) to actionable R output.

Statistics R Programming

What Is a Linear Model?

A linear model describes the relationship between a response variable \( y \) and one or more predictor variables \( x \). The simplest form is simple linear regression:

The goal: find \( \hat{\beta}_0 \) and \( \hat{\beta}_1 \) that best fit the observed data by minimizing the sum of squared residuals.

Why lm() Matters

Prediction
Estimate future outcomes from known relationships: predict sales from ad spend, grades from study hours.
Inference
Test whether a predictor truly influences the response using p-values and confidence intervals.
Foundation
Nearly every advanced statistical method (ANOVA, GLMs, mixed models) extends the linear model framework.

Visualizing the Best Fit Line

Hours Studied (x) Exam Score (y) 1 3 5 7 9 50 60 70 80 90 Data points Fit

Ordinary Least Squares: The Math

OLS finds \( \hat{\beta}_0 \) and \( \hat{\beta}_1 \) by minimizing the residual sum of squares:

Slope
\( \hat{\beta}_1 = \dfrac{\sum (x_i - \bar{x})(y_i - \bar{y})}{\sum (x_i - \bar{x})^2} \)
Intercept
\( \hat{\beta}_0 = \bar{y} - \hat{\beta}_1 \bar{x} \)

R's lm() performs these calculations automatically. You supply the formula and data: R returns the estimates.

The lm() Function Syntax

# Basic syntax lm(formula, data) # Example: predict exam score from hours studied model <- lm(score ~ hours, data = students)

The data argument tells R which data frame contains the variables. Always specify it: this keeps your code clean and reproducible.

lm() vs cor() vs plot()

lm() cor() plot()
Purpose Fit a regression model Compute correlation Visualize relationship
Output Coefficients, p-values, \( R^2 \) Single number (\( r \)) Scatter plot
Prediction ✓ Yes ✕ No ✕ No
Directionality \( y \) depends on \( x \) Symmetric Visual only
Formula input ✓ Yes ✕ No Optional

How to Apply: Step by Step

1
Explore your data. Use plot(y \( \sim \) x) to check for linearity, outliers, and spread.
2
Fit the model. Store the result: model <- lm(y \( \sim \) x, data = df).
3
Read the summary. Call summary(model) to see coefficients, p-values, and \( R^2 \).
4
Diagnose. Run plot(model) to check residual assumptions (normality, constant variance).
5
Predict. Use predict(model, newdata = ...) to generate predictions for new observations.

Example 1: Fitting a Model

# Create some data hours <- c(1, 2, 3, 4, 5, 5, 6, 7, 8, 9) scores <- c(52, 55, 62, 65, 70, 68, 73, 78, 82, 88) students <- data.frame(hours, scores) # Fit the linear model model <- lm(scores ~ hours, data = students) # View coefficients coef(model)
## (Intercept) hours ## 47.216667 4.416667

Example 2: Reading summary()

summary(model)
## Coefficients: ## Estimate Std. Error t value Pr(>|t|) ## (Intercept) 47.2167 1.8498 25.525 1.51e-08 *** ## hours 4.4167 0.3236 13.651 7.71e-07 *** ## --- ## Residual standard error: 2.043 on 8 degrees of freedom ## Multiple R-squared: 0.9589, Adjusted R-squared: 0.9537 ## F-statistic: 186.3 on 1 and 8 DF, p-value: 7.71e-07
Estimate
\( \hat{\beta}_0 \) and \( \hat{\beta}_1 \) values
Pr(>|t|)
p-value: < 0.05 means statistically significant
\( R^2 \)
0.959: hours explains 95.9% of score variation

Example 3: Making Predictions

# Predict score for a student who studies 6.5 hours new_data <- data.frame(hours = 6.5) predict(model, newdata = new_data)
## 1 ## 75.925
# Add confidence interval predict(model, newdata = new_data, interval = "confidence")
## fit lwr upr ## 1 75.925 73.548 78.302

Interpreting Coefficients

x y Intercept (\( \hat{\beta}_0 \)) \( \text{run} = 1 \) \( \text{rise} \) Slope \( (\hat{\beta}_1) = \frac{\text{rise}}{\text{run}} \)
\( \hat{\beta}_0 \) (Intercept)
"When \( x = 0 \), the predicted \( y \) is \( \hat{\beta}_0 \)." Sometimes meaningful, sometimes not (can \( x = 0 \) occur?).
\( \hat{\beta}_1 \) (Slope)
"For each 1-unit increase in \( x \), \( y \) changes by \( \hat{\beta}_1 \) units on average." This is the key coefficient.

Understanding \( R^2 \)

\( R^2 \) tells you the proportion of variance in \( y \) explained by \( x \). It ranges from 0 (model explains nothing) to 1 (perfect fit).

0% 100% \( R^2 = 0.959 \) 95.9% of variance explained

Checking Residual Assumptions

# Generate 4 diagnostic plots par(mfrow = c(2, 2)) plot(model)
Residuals vs Fitted
Should show no pattern: random scatter around 0. A curve means the relationship is non-linear.
Normal Q-Q
Points should follow the diagonal line. Deviations indicate non-normal residuals.
Scale-Location
Check for constant variance (homoscedasticity). A funnel shape is a warning sign.
Cook's Distance
Identifies influential points. Values > 0.5 or 1 deserve closer inspection.

Common Mistakes

✕ Wrong Formula Direction
Writing lm(x \( \sim \) y) instead of lm(y \( \sim \) x). The response variable always goes on the left of the tilde.
✕ Forgetting data =
Omitting the data argument and relying on global variables. This makes code fragile and hard to debug.
✕ Confusing \( R^2 \) with Causation
A high \( R^2 \) means good fit, not that \( x \) causes \( y \). Correlation is not causation: always consider confounders.
✕ Ignoring Residual Plots
Reporting coefficients without checking assumptions. Non-linear data, heteroscedasticity, and outliers invalidate OLS results.

Key Functions Summary

Function Purpose Key Output
lm(y ~ x, data) Fit linear model Model object
summary(model) Full report Coefficients, p-values, \( R^2 \)
coef(model) Extract coefficients \( \hat{\beta}_0 \), \( \hat{\beta}_1 \)
predict(model, newdata) Generate predictions Fitted \( \hat{y} \) values
residuals(model) Extract residuals \( y_i - \hat{y}_i \)
plot(model) Diagnostic plots 4 residual diagnostic plots
confint(model) Confidence intervals 95% CI for coefficients

Question 1 of 5

In the R formula lm(weight ~ height, data = df), which variable is the response?

Question 2 of 5

A model has \( \hat{\beta}_0 = 10 \) and \( \hat{\beta}_1 = 3 \). What is the predicted value of \( y \) when \( x = 5 \)?

Question 3 of 5

An \( R^2 \) value of 0.82 means:

Question 4 of 5

Which R function would you use to get the p-values and \( R^2 \) from a fitted linear model?

Question 5 of 5

When the "Residuals vs Fitted" diagnostic plot shows a clear curved pattern, what does this indicate?