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.
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
Visualizing the Best Fit Line
Ordinary Least Squares: The Math
OLS finds \( \hat{\beta}_0 \) and \( \hat{\beta}_1 \) by minimizing the residual sum of squares:
R's lm() performs these calculations automatically. You supply the formula and data: R returns the estimates.
The lm() Function Syntax
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
Example 1: Fitting a Model
Example 2: Reading summary()
Example 3: Making Predictions
Interpreting Coefficients
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).
Checking Residual Assumptions
Common Mistakes
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?