11.1 A path for a new dataset
Use this note as the checklist for a project. The question is: you have a new table, and you may end up fitting a model. Do the steps in order. 6.3 Exploratory data analysis is the longer version of the looking. 11.2 Comparisons: tests is the catalog for a question that is a comparison of means, a proportion, or a table of counts, rather than a model of a numeric outcome.
The running example is mtcars. mpg is miles
per gallon, wt is weight in thousands of pounds,
disp is engine size, hp is horsepower, and
am is the transmission (0 automatic, 1 manual).
1. Review what Week 6 already did
Once the file is in and the types look right, look before you model.
Week 6 uses diamonds for the full set of plots. The order
is the same on any table:
- one variable at a time: type, range, a bar or a histogram, and the count of missing values
- every pair that might matter: a scatter, a boxplot, or a table of counts
- a third variable, as color or as facets
- missingness and points that sit off the pattern
Name the pattern before you fit anything: straight, bent, grouped, or no pattern. Do not delete an odd point until you know whether it is a data error or a real case. The mosaic plots and the import details stay in note 6.3.
On mtcars, do that pass for the columns a fuel-economy
question might use. There are no missing values.
library(tidyverse)
summary(mtcars[c("mpg", "wt", "disp", "hp")])
## mpg wt disp hp
## Min. :10.40 Min. :1.513 Min. : 71.1 Min. : 52.0
## 1st Qu.:15.43 1st Qu.:2.581 1st Qu.:120.8 1st Qu.: 96.5
## Median :19.20 Median :3.325 Median :196.3 Median :123.0
## Mean :20.09 Mean :3.217 Mean :230.7 Mean :146.7
## 3rd Qu.:22.80 3rd Qu.:3.610 3rd Qu.:326.0 3rd Qu.:180.0
## Max. :33.90 Max. :5.424 Max. :472.0 Max. :335.0
mpg against wt is a straight downward tilt.
mpg against hp falls quickly and then
flattens. Those two pictures decide the models later: a line in weight,
a curve in horsepower.
ggplot(mtcars, aes(x = wt, y = mpg)) +
geom_point() +
geom_smooth(method = lm, se = FALSE) +
theme_bw()

ggplot(mtcars, aes(x = hp, y = mpg)) +
geom_point() +
geom_smooth(se = FALSE) +
theme_bw()

geom_smooth() with no method is a loess
curve. Use it to see a bend. The model you report comes after that
picture.
A third variable: transmission, as color on the weight plot. The manual cars sit toward the light end of the cloud.
ggplot(mtcars, aes(x = wt, y = mpg, color = factor(am))) +
geom_point() +
theme_bw()

2. Name the outcome
A model needs one column as the outcome and a short list of
candidates. Here the outcome is mpg. The candidates, from
the question “what goes with fuel economy in this table,” are
wt, disp, hp, and
am. A column that you cannot explain in that sentence does
not enter the list.
3. Choose the predictors
Several candidates can tell the same story. Variable selection, in this course, is three decisions.
- Start from the question. A column is a candidate because it belongs in the sentence you want to write.
- Among the numeric candidates, look for redundancy. Two columns that move together are two measurements of one thing. Keep the one that matches the question.
- After a first fit, ask whether one extra candidate still helps. That
is
anova()on two nested models.
cor() is the redundancy check. It is correlation among
the candidates, not a test yet.
round(cor(mtcars[c("wt", "disp", "hp")]), 2)
## wt disp hp
## wt 1.00 0.89 0.66
## disp 0.89 1.00 0.79
## hp 0.66 0.79 1.00
Weight and engine size move together (correlation about 0.89). Both
say “this car is large.” Horsepower moves with them too, but less
tightly with weight (about 0.66). Keep wt for size, because
the question can be stated in pounds. Leave disp out.
Keeping both would split one size story across two coefficients.
The nested comparison is the second check. The smaller model is a special case of the larger one. H0: the extra term is zero.
anova(
lm(mpg ~ wt, data = mtcars),
lm(mpg ~ wt + disp, data = mtcars)
)
## Analysis of Variance Table
##
## Model 1: mpg ~ wt
## Model 2: mpg ~ wt + disp
## Res.Df RSS Df Sum of Sq F Pr(>F)
## 1 30 278.32
## 2 29 246.68 1 31.639 3.7195 0.06362 .
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
Once weight is in the model, engine size does not clearly help (p about 0.06). Horsepower does:
anova(
lm(mpg ~ wt, data = mtcars),
lm(mpg ~ wt + hp, data = mtcars)
)
## Analysis of Variance Table
##
## Model 1: mpg ~ wt
## Model 2: mpg ~ wt + hp
## Res.Df RSS Df Sum of Sq F Pr(>F)
## 1 30 278.32
## 2 29 195.05 1 83.274 12.381 0.001451 **
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
p is about 0.001. The candidates that remain are wt and
hp.
Transmission is a useful caution. mpg and
am move together (correlation about 0.60), and the colored
scatter shows a difference. After weight is in the model, transmission
adds nothing:
anova(
lm(mpg ~ wt, data = mtcars),
lm(mpg ~ wt + factor(am), data = mtcars)
)
## Analysis of Variance Table
##
## Model 1: mpg ~ wt
## Model 2: mpg ~ wt + factor(am)
## Res.Df RSS Df Sum of Sq F Pr(>F)
## 1 30 278.32
## 2 29 278.32 1 0.0022403 2e-04 0.9879
p is about 0.99. The manual cars in this table are mostly the light cars, so the transmission gap was a weight gap. A column can look important alone and still be redundant once the right predictor is present.
Stepwise regression and AIC are automatic searches: the function tries adding and dropping columns to improve a score. Leave them out of the project. They follow this sample, and they hide the question you started with. The selection here is the question, the correlations, and one nested comparison.
4. Predictors on different scales
wt runs from about 1.5 to about 5.4. hp
runs from about 50 to about 340. This is a different problem from
redundancy. Both columns stay. Their raw coefficients are just in
different units:
- the
wtcoefficient is the change inmpgfor one thousand pounds - the
hpcoefficient is the change inmpgfor one horsepower
One horsepower is a tiny step next to a thousand pounds, so the
hp coefficient looks close to zero even when horsepower
matters. Ranking the raw coefficients, or comparing their p-values to
decide which variable is “more important,” misreads the units.
Three honest ways to talk about them:
- Say the unit. “About −3.9 mpg per thousand pounds,
holding horsepower fixed. About −0.03 mpg per horsepower, holding weight
fixed.” You can also rescale a predictor so one unit is a step you care
about:
I(hp / 10)makes the coefficient “per 10 horsepower.” - Standardize, then compare. Subtract the mean and
divide by the standard deviation. Each coefficient is then the change in
mpgfor a one-standard-deviation step in that predictor.
mt_z <- mtcars |>
mutate(
wt_z = scale(wt)[, 1],
hp_z = scale(hp)[, 1]
)
fit_raw <- lm(mpg ~ wt + hp, data = mt_z)
fit_z <- lm(mpg ~ wt_z + hp_z, data = mt_z)
broom::tidy(fit_raw)
## # A tibble: 3 × 5
## term estimate std.error statistic p.value
## <chr> <dbl> <dbl> <dbl> <dbl>
## 1 (Intercept) 37.2 1.60 23.3 2.57e-20
## 2 wt -3.88 0.633 -6.13 1.12e- 6
## 3 hp -0.0318 0.00903 -3.52 1.45e- 3
broom::tidy(fit_z)
## # A tibble: 3 × 5
## term estimate std.error statistic p.value
## <chr> <dbl> <dbl> <dbl> <dbl>
## 1 (Intercept) 20.1 0.458 43.8 4.69e-28
## 2 wt_z -3.79 0.619 -6.13 1.12e- 6
## 3 hp_z -2.18 0.619 -3.52 1.45e- 3
Read the two tables together. The estimates change. The p-values for
wt and hp do not. Standardizing multiplies a
coefficient and its standard error by the same factor, so the test of
“this coefficient is zero” is the same test as before.
The raw estimates are about −3.88 mpg per thousand pounds and about −0.032 mpg per horsepower. The standardized estimates are about −3.79 and −2.18, both in mpg per standard deviation. Weight has the larger partial association. That is a comparison of association size. It is not a causal ranking.
The intercept in fit_z is the fitted mpg
when weight and horsepower are at their means. The fitted values of
fit_raw and fit_z match. The plane is the same
plane.
- When the outcome itself spans orders of magnitude
(prices, counts, areas), a log of
yis often the right scale. That is about the shape of the outcome. Section 6 showslog(mpg)when the residual spread fans out.
Standardize when you want to compare predictors. Do it because the units differ.
5. Fit the line
lm(y ~ x1 + x2) is ordinary least squares: a plane that
minimizes squared errors. Linear
regression in R, step by step (StatQuest) reads the same
summary.
fit <- lm(mpg ~ wt + hp, data = mtcars)
summary(fit)
##
## Call:
## lm(formula = mpg ~ wt + hp, data = mtcars)
##
## Residuals:
## Min 1Q Median 3Q Max
## -3.941 -1.600 -0.182 1.050 5.854
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 37.22727 1.59879 23.285 < 2e-16 ***
## wt -3.87783 0.63273 -6.129 1.12e-06 ***
## hp -0.03177 0.00903 -3.519 0.00145 **
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 2.593 on 29 degrees of freedom
## Multiple R-squared: 0.8268, Adjusted R-squared: 0.8148
## F-statistic: 69.21 on 2 and 29 DF, p-value: 9.109e-12
coef(fit)
## (Intercept) wt hp
## 37.22727012 -3.87783074 -0.03177295
confint(fit)
## 2.5 % 97.5 %
## (Intercept) 33.95738245 40.49715778
## wt -5.17191604 -2.58374544
## hp -0.05024078 -0.01330512
broom::tidy(fit, conf.int = TRUE)
## # A tibble: 3 × 7
## term estimate std.error statistic p.value conf.low conf.high
## <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
## 1 (Intercept) 37.2 1.60 23.3 2.57e-20 34.0 40.5
## 2 wt -3.88 0.633 -6.13 1.12e- 6 -5.17 -2.58
## 3 hp -0.0318 0.00903 -3.52 1.45e- 3 -0.0502 -0.0133
Install broom once in the console if it is missing. Do
not put install.packages() in the Quarto file.
Read one row in three numbers.
- The estimate is the size, in the unit of that
predictor. The
wtnumber is the change in fittedmpgfor one extra thousand pounds, holdinghpfixed. - The interval is the range of coefficients still compatible with this table.
- The p-value is the surprise under H0: this coefficient is zero. A small p-value is evidence against that claim. It is not the probability that the claim is true, and it is not the size of the effect. A large p-value is a weak case against H0. It does not prove the coefficient is zero.
R-squared is the share of variance in mpg that this
plane lines up with. A high R-squared with a bent residual plot is still
a bad description.
Note 11.2 uses the same three numbers for a comparison of groups. The hypothesis procedure there (write H0, plot, then test) is the one to follow when the project question is a comparison rather than this line.
6. Residual plots
A residual is observed minus fitted. If the model is a good description, residuals look like unstructured noise around zero. What is a residual plot? (Zach’s Math Zone) is a short picture of that plot.
plot(fit, which = 1)

plot(fit, which = 2)

which = 1 is residuals versus fitted.
which = 2 is the normal QQ plot. Quantile-quantile
plots, clearly explained (StatQuest) is that second plot.
aug <- broom::augment(fit)
ggplot(aug, aes(x = .fitted, y = .resid)) +
geom_point() +
geom_hline(yintercept = 0) +
geom_smooth(se = FALSE) +
theme_bw()

If the residual cloud fans out, try a transform of
the response, often log(y), and look again:
fit_log <- lm(log(mpg) ~ wt + hp, data = mtcars)
plot(fit_log, which = 1)

A curve left in the residuals is a reason to try the spline in section 7. A fan is a reason to try a transform.
7. A bend: splines
The horsepower scatter bends, so a line in hp alone
leaves a curve behind. A spline is a curve built from polynomial pieces
that meet smoothly. It stays inside lm().
splines::ns(x, df = 3) builds a natural spline with 3
degrees of freedom. More degrees of freedom allow more bends. Start at 3
or 4. Add a degree of freedom only when the residual plot still shows a
bend.
fit_line <- lm(mpg ~ hp, data = mtcars)
fit_spline <- lm(mpg ~ splines::ns(hp, df = 3), data = mtcars)
The grey line is the linear fit. The blue curve is the spline.
ggplot(mtcars, aes(x = hp, y = mpg)) +
geom_point() +
geom_smooth(method = lm, se = FALSE, color = "grey40") +
geom_smooth(
method = lm,
formula = y ~ splines::ns(x, df = 3),
se = FALSE,
color = "steelblue"
) +
theme_bw()

The line is nested in the spline. H0: a straight line in
hp is enough for mpg.
anova(fit_line, fit_spline)
## Analysis of Variance Table
##
## Model 1: mpg ~ hp
## Model 2: mpg ~ splines::ns(hp, df = 3)
## Res.Df RSS Df Sum of Sq F Pr(>F)
## 1 30 447.67
## 2 28 269.05 2 178.63 9.295 0.0008019 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
A small p-value is evidence that the bend is real in this table. It
is not a reason to keep raising df. Check the residuals of
the spline. If they are a flat cloud, stop.
plot(fit_spline, which = 1)

splines::bs() is the other base-R spline. Reach for
ns() first: it is linear beyond the outer data points, so
the ends do not swing as hard. The loess curve from section 1 is how you
see the bend. Report lm() with ns() when you
need a comparison and a p-value.
8. A group, when the question is a comparison
If the project question is “do these groups differ?” and there is no
line to fit, use note 11.2. That note is the t-test, the z-test,
aov() for three or more means, a proportion, and
chi-square.
If a group column is one more candidate in a model you are already
fitting, code it as a factor and use the same nested
anova() as in section 3. factor(am) in section
3 was that case: it did not help once weight was included.
9. The checklist
| Where you are | What you do | What you keep |
|---|---|---|
| a new table | Week 6 order: one variable, pairs, a third variable, missing values. Link in section 1 | a named pattern: straight, bent, grouped, or none |
| before any model | name the outcome and the candidates that belong in the question | a short list, not every column |
| two candidates move together | cor() on the candidates. Keep the column the question
can state. Then anova(small, big) for one extra column |
one of the redundant columns. Stepwise and AIC stay unused |
| a straight cloud, similar spread | lm(y ~ x1 + x2). Read the estimate, the interval, and
the p-value for “this coefficient is zero” |
the coefficient in its real unit |
| the columns you kept use different units and you want to compare them | standardize, then refit | the larger standardized magnitude is the larger partial association.
Slope p-values and fitted values stay the same. On
mpg ~ wt + hp, raw coefficients of about −3.88 and −0.032
become about −3.79 and −2.18 |
| residuals fan out | refit with log(y) and look again |
a description of the outcome’s scale |
| the cloud bends | lm(y ~ splines::ns(x, df = 3)), then
anova() against the line, then the residual plot |
the curve when the residual plot goes flat. Stop adding degrees of freedom |
| the question is only whether groups differ | note 11.2 | the estimate, the interval, and the p-value against a written H0 |
10. Practice
- In
mtcars, correlation ofwt,disp, andhp. Which pair is redundant for a question about the size of the car? Fitmpg ~ wtandmpg ~ wt + disp. State H0 for theanova()and say whether engine size still helps. - Scatter of
mpgagainsthp, with a straight line and withsplines::ns(hp, df = 3). Fit both withlm(). Useanova()and state H0 in words. Look atplot(fit_spline, which = 1). fit <- lm(mpg ~ wt + hp, data = mtcars). Write one sentence for thewtcoefficient that includes its unit. Refit with the standardized columns from section 4 and say which standardized coefficient is larger in magnitude.