library(tidyverse)
library(broom) # tidy(), glance(): model results as tibbles
library(ggstats) # ggcoef_model(): plots of model coefficients
library(palmerpenguins)Intro to Linear Models
Predicting penguin body mass with lm()
What is a linear model?
A linear model predicts one numeric variable (the response) from one or more other variables (the predictors) with a straight-line formula:
\[ \text{body mass} = b_0 + b_1 \cdot \text{bill length} + \dots \]
R finds the coefficients \(b_0, b_1, \dots\) that make the predictions as close to the real data as possible (least squares). The function is lm(), short for linear model.
In this lesson we ask: how well can we predict a penguin’s body mass from its measurements?
We use the penguins data from the palmerpenguins package. The measurements are bill_length_mm, bill_depth_mm, flipper_length_mm and body_mass_g.
glimpse(penguins)Rows: 344
Columns: 8
$ species <fct> Adelie, Adelie, Adelie, Adelie, Adelie, Adelie, Adel…
$ island <fct> Torgersen, Torgersen, Torgersen, Torgersen, Torgerse…
$ bill_length_mm <dbl> 39.1, 39.5, 40.3, NA, 36.7, 39.3, 38.9, 39.2, 34.1, …
$ bill_depth_mm <dbl> 18.7, 17.4, 18.0, NA, 19.3, 20.6, 17.8, 19.6, 18.1, …
$ flipper_length_mm <int> 181, 186, 195, NA, 193, 190, 181, 195, 193, 190, 186…
$ body_mass_g <int> 3750, 3800, 3250, NA, 3450, 3650, 3625, 4675, 3475, …
$ sex <fct> male, female, female, NA, female, male, female, male…
$ year <int> 2007, 2007, 2007, 2007, 2007, 2007, 2007, 2007, 2007…
One predictor
Fitting the model
The formula body_mass_g ~ bill_length_mm reads “body mass, predicted by bill length.”
m_len <- lm(body_mass_g ~ bill_length_mm, data = penguins)
m_len
Call:
lm(formula = body_mass_g ~ bill_length_mm, data = penguins)
Coefficients:
(Intercept) bill_length_mm
362.31 87.42
The output has two coefficients:
- (Intercept): the predicted mass of a penguin with a 0 mm bill. That’s not meaningful on its own; it just positions the line.
- bill_length_mm: the slope. Each extra millimeter of bill length predicts about 87 more grams of body mass.
Seeing the model
geom_smooth(method = "lm") draws the same line lm() computes. The grey band shows the uncertainty in the line.
ggplot(penguins, aes(bill_length_mm, body_mass_g)) +
geom_point(alpha = 0.5) +
geom_smooth(method = "lm") +
labs(x = "Bill length (mm)", y = "Body mass (g)")
Reading summary()
summary() shows much more: a standard error, a t value and a p-value for each coefficient, and R² for the whole model.
summary(m_len)
Call:
lm(formula = body_mass_g ~ bill_length_mm, data = penguins)
Residuals:
Min 1Q Median 3Q Max
-1762.08 -446.98 32.59 462.31 1636.86
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 362.307 283.345 1.279 0.202
bill_length_mm 87.415 6.402 13.654 <2e-16 ***
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
Residual standard error: 645.4 on 340 degrees of freedom
(2 observations deleted due to missingness)
Multiple R-squared: 0.3542, Adjusted R-squared: 0.3523
F-statistic: 186.4 on 1 and 340 DF, p-value: < 2.2e-16
- Estimate: the coefficient itself.
- Std. Error: how uncertain that estimate is.
- Pr(>|t|): the p-value. It answers: if bill length really had no relationship with mass, how likely is a slope this far from 0? A p-value below 0.05 is usually called statistically significant. Here it’s tiny, so the relationship is very unlikely to be a fluke.
- Multiple R-squared: the share of the variation in body mass the model explains, from 0 (none) to 1 (all). Bill length alone explains about 35%.
Results as a tibble with broom
summary() is made for reading, not for computing with. tidy() returns the same coefficient table as a tibble, and glance() returns one row of whole-model statistics.
tidy(m_len)# A tibble: 2 × 5
term estimate std.error statistic p.value
<chr> <dbl> <dbl> <dbl> <dbl>
1 (Intercept) 362. 283. 1.28 2.02e- 1
2 bill_length_mm 87.4 6.40 13.7 3.81e-34
glance(m_len) |> select(r.squared, sigma, p.value, nobs)# A tibble: 1 × 4
r.squared sigma p.value nobs
<dbl> <dbl> <dbl> <int>
1 0.354 645. 3.81e-34 342
sigma is the typical prediction error, in grams: this model’s predictions are usually off by about 650 g.
Many predictors
Using every numeric variable
The formula body_mass_g ~ . means “predict body mass from every other column.” We keep only the numeric columns first, because each column becomes a predictor.
penguins_num <- penguins |>
select(where(is.numeric))
m_all <- lm(body_mass_g ~ ., data = penguins_num)
tidy(m_all)# A tibble: 5 × 5
term estimate std.error statistic p.value
<chr> <dbl> <dbl> <dbl> <dbl>
1 (Intercept) 210420. 52075. 4.04 6.61e- 5
2 bill_length_mm 2.18 5.23 0.418 6.76e- 1
3 bill_depth_mm 23.9 13.4 1.78 7.55e- 2
4 flipper_length_mm 52.2 2.46 21.2 6.11e-64
5 year -108. 26.0 -4.16 3.97e- 5
In a model with several predictors, each coefficient is the effect of that variable holding the others fixed, and its p-value asks whether that variable helps beyond the others already in the model.
Plotting the coefficients with ggcoef_model()
ggcoef_model() draws each coefficient as a point with its 95% confidence interval. It returns a ggplot, so you can add a title with labs() as usual. A filled point is significant (p < 0.05); a hollow point, whose interval crosses 0, is not.
ggcoef_model(m_all) +
labs(title = "Predicting body mass from numeric variables")
Things to notice:
flipper_length_mmis by far the strongest predictor.bill_length_mmis no longer significant, even though it was very significant on its own. Flipper length already carries most of the same information.yearcomes out significant, but it’s the date the penguin was measured, not a feature of the penguin. Including every numeric column without thinking about what it means can add misleading predictors like this.
Engineering a new variable
Bill ratio
A long, narrow bill and a short, thick bill can have the same length. The ratio of length to depth captures bill shape:
penguins_num <- penguins_num |>
mutate(bill_ratio = bill_length_mm / bill_depth_mm)Which predicts better: bill length or bill ratio?
The simplest comparison: fit one model per predictor and compare R² and sigma.
m_ratio <- lm(body_mass_g ~ bill_ratio, data = penguins_num)
bind_rows(
bill_length_mm = glance(m_len),
bill_ratio = glance(m_ratio),
.id = "predictor"
) |>
select(predictor, r.squared, sigma)# A tibble: 2 × 3
predictor r.squared sigma
<chr> <dbl> <dbl>
1 bill_length_mm 0.354 645.
2 bill_ratio 0.494 571.
Bill ratio wins: it explains more of the variation (higher R²), and its predictions are closer to the truth (lower sigma, in grams).
R² is a fair comparison here because both models have exactly one predictor. Adding predictors never lowers R², so to compare models of different sizes, use adj.r.squared or AIC (lower is better) instead.
A strong predictor that isn’t significant
Now put bill ratio in a model with flipper length:
m_both <- lm(body_mass_g ~ flipper_length_mm + bill_ratio, data = penguins_num)
tidy(m_both)# A tibble: 3 × 5
term estimate std.error statistic p.value
<chr> <dbl> <dbl> <dbl> <dbl>
1 (Intercept) -5757. 381. -15.1 7.20e-40
2 flipper_length_mm 49.5 2.56 19.3 1.69e-56
3 bill_ratio 7.60 72.5 0.105 9.17e- 1
Bill ratio’s p-value is now large: it’s not significant. How can a strong predictor stop mattering?
Bill ratio and flipper length are strongly correlated, because both mostly tell you the species:
penguins |>
mutate(bill_ratio = bill_length_mm / bill_depth_mm) |>
group_by(species) |>
summarize(
bill_ratio = mean(bill_ratio, na.rm = TRUE),
flipper_length_mm = mean(flipper_length_mm, na.rm = TRUE),
body_mass_g = mean(body_mass_g, na.rm = TRUE)
)# A tibble: 3 × 4
species bill_ratio flipper_length_mm body_mass_g
<fct> <dbl> <dbl> <dbl>
1 Adelie 2.12 190. 3701.
2 Chinstrap 2.65 196. 3733.
3 Gentoo 3.18 217. 5076.
Gentoos have the narrowest bills, the longest flippers and the most mass. Once flipper length has identified “a big Gentoo,” bill shape adds nothing new. A p-value in a multiple regression is about what a variable adds beyond the others, not how strongly it’s related to the response.
A caution: predicting a category
Linear models predict numbers. It’s tempting to predict species by coding it as a number:
p_species <- penguins |> select(species) |> distinct() |> pull()
p_species[1] Adelie Gentoo Chinstrap
Levels: Adelie Chinstrap Gentoo
penguins_coded <- penguins |>
mutate(
species_num = case_when(
species == p_species[1] ~ 1,
species == p_species[2] ~ 2,
species == p_species[3] ~ 3
)
) |>
select(where(is.numeric))
m_species <- lm(species_num ~ ., data = penguins_coded)
ggcoef_model(m_species) +
labs(title = "Predicting species (coded 1, 2, 3)")
R happily fits this, but the result doesn’t mean much. The codes come from the order the species first appear in the data, so Gentoo is 2 and Chinstrap is 3, and the model treats Chinstrap as “one more” than Gentoo. Code the species in a different order and you get different coefficients from the same data. For categories, use a classification method instead, such as logistic regression (glm(..., family = binomial)) for two groups.
Summary
| Task | Code |
|---|---|
| Fit a model | lm(response ~ predictor, data = df) |
| Use every other column | lm(response ~ ., data = df) |
| Coefficients and p-values | summary(model) or tidy(model) |
| R² and prediction error | glance(model) |
| Plot the coefficients | ggcoef_model(model) |
Try it yourself
- Predict
body_mass_gfromflipper_length_mmalone. How does its R² compare with bill length and bill ratio? - Fit
lm(body_mass_g ~ flipper_length_mm + species, data = penguins). How does R handle thespeciescolumn, and what do its coefficients mean? - Drop
yearfrompenguins_numand refitm_all. Which coefficients change? - Find two numeric variables in another dataset (e.g.
swissormtcars) and compare their predictive power withglance().