set.seed(801)
boot <- map_dfr(1:2000, \(i) {
idx <- sample(n, replace = TRUE)
b <- coef(lm(birthweight ~ estriol, data = estriol_df[idx, ]))
tibble(intercept = b[1], slope = b[2])
})
sd(boot$slope)[1] 0.1611105
mean(boot$slope <= 0)[1] 0
In Chapter 11 we fitted a line to 31 pregnancies. The slope was 0.608: each extra mg/24 h of maternal estriol went with 61 g more birthweight. A different set of mothers gives a different line, so the slope and each prediction have an uncertainty.
The obstetrician has two questions about the estriol data (Greene and Touchstone, 1963, as given in Rosner, Fundamentals of Biostatistics).
Is the estriol slope real, or can chance alone make a slope this large in 31 pregnancies? And how well can we predict the birthweight of one baby?
The first question is about the population line. The second is about one new mother. A new mother has 10 mg/24 h of estriol. The fitted line predicts 27.6 units, or 2.76 kg. This is above the 2.5 kg cut-off for low birthweight. The obstetrician wants to know how much to trust that number.
We have only one sample of 31 pregnancies. The bootstrap makes new samples from it. We draw 31 pregnancies at random, with replacement, from the original 31. Some mothers occur twice and some do not occur. We fit a line to each new sample. The spread of these lines shows how much the line changes from sample to sample.
set.seed(801)
boot <- map_dfr(1:2000, \(i) {
idx <- sample(n, replace = TRUE)
b <- coef(lm(birthweight ~ estriol, data = estriol_df[idx, ]))
tibble(intercept = b[1], slope = b[2])
})
sd(boot$slope)[1] 0.1611105
mean(boot$slope <= 0)[1] 0
p_lines <- ggplot(estriol_df, aes(estriol, birthweight)) +
geom_abline(data = slice_head(boot, n = 200), aes(intercept = intercept, slope = slope),
colour = "grey60", alpha = 0.25) +
geom_point(colour = "steelblue", size = 1.8) +
geom_abline(intercept = coef(fit)[1], slope = b1, colour = "firebrick", linewidth = 1) +
labs(x = "maternal estriol (mg/24 h)", y = "birthweight (100 g)")
p_slopes <- ggplot(boot, aes(slope)) +
geom_histogram(binwidth = 0.03, fill = "steelblue", colour = "white") +
geom_vline(xintercept = 0, linetype = "dashed", colour = "grey40") +
geom_vline(xintercept = b1, colour = "firebrick") +
labs(x = "bootstrap slope", y = "count")
p_lines + p_slopes
The lines form a fan. They are close together near the middle of the data and spread out at the ends. The bootstrap slopes have a standard deviation of 0.161. This number estimates the standard error of the slope. Not one of the 2,000 bootstrap slopes is zero or negative.
A shuffle shows what chance alone can do. If estriol and birthweight have no relation, any pairing of mothers and babies is equally likely. We shuffle the birthweights 5,000 times and fit a line each time, as in Chapter 2.
set.seed(802)
null_slopes <- replicate(5000, {
coef(lm(sample(birthweight) ~ estriol, data = estriol_df))[2]
})
mean(abs(null_slopes) >= abs(b1))[1] 2e-04
max(abs(null_slopes))[1] 0.6229524
The largest shuffled slope is 0.623 in absolute value. Only 1 of the 5,000 shuffles gives a slope as large as 0.608. Chance alone rarely makes a slope like ours, so the data give strong evidence of a real relation.
The fan of lines also answers the second question in part. It shows the uncertainty about the mean birthweight at each estriol level. One baby varies around that mean as well, so the uncertainty for one baby is larger. The formal section separates these two parts.
Under the LINE assumptions, the estimates have these variances:
\[ \operatorname{Var}(\hat\beta_1) = \frac{\sigma^2}{S_{xx}}, \qquad \operatorname{Var}(\hat\beta_0) = \sigma^2\left(\frac{1}{n} + \frac{\bar x^2}{S_{xx}}\right), \qquad S_{xx} = \sum_i (x_i - \bar x)^2 . \]
These formulas follow from the fact that the slope is a weighted sum of the responses. Because \(\sum_i (x_i - \bar x)\,\bar y = 0\),
\[ \hat\beta_1 = \frac{\sum_i (x_i - \bar x)(y_i - \bar y)}{S_{xx}} = \sum_i c_i\, y_i, \qquad c_i = \frac{x_i - \bar x}{S_{xx}} . \]
The weights have three properties: \(\sum_i c_i = 0\), \(\sum_i c_i x_i = 1\) and \(\sum_i c_i^2 = 1/S_{xx}\).
In matrix form, \(\hat{\boldsymbol\beta} = \mathbf A\mathbf y\) with \(\mathbf A = (\mathbf X^\top\mathbf X)^{-1}\mathbf X^\top\). Then \(\operatorname{Var}(\hat{\boldsymbol\beta}) = \mathbf A(\sigma^2\mathbf I)\mathbf A^\top = \sigma^2(\mathbf X^\top\mathbf X)^{-1}\). The diagonal of this matrix holds the two variances above, and Chapter 14 uses the same result with more columns. We check the weights and the matrix result on the estriol data:
x <- estriol_df$estriol
w <- (x - mean(x)) / sum((x - mean(x))^2)
c(sum_c = sum(w), sum_cx = sum(w * x), slope = sum(w * estriol_df$birthweight), coef_lm = unname(coef(fit)[2])) sum_c sum_cx slope coef_lm
-3.295975e-17 1.000000e+00 6.081905e-01 6.081905e-01
X <- model.matrix(fit)
all.equal(vcov(fit), sigma(fit)^2 * solve(t(X) %*% X), check.attributes = FALSE)[1] TRUE
The variance of the slope is small when the noise \(\sigma^2\) is small and when the \(x\) values are spread out. A study that measures mothers with a wide range of estriol estimates the slope better. The formulas need L, I and E from Chapter 11.
We do not know \(\sigma\). We estimate it with the residual standard error, \(s = \sqrt{\text{RSS}/(n-2)}\). The standard error (SE) is the square root of the variance with \(s\) in place of \(\sigma\).
x <- estriol_df$estriol
s <- sqrt(sum(residuals(fit)^2) / (n - 2))
Sxx <- sum((x - mean(x))^2)
c(s = s,
se_b1 = s / sqrt(Sxx),
se_b0 = s * sqrt(1 / n + mean(x)^2 / Sxx)) s se_b1 se_b0
3.8211098 0.1468117 2.6204170
The formula gives SE(\(\hat\beta_1\)) = 0.147. The bootstrap gave 0.161. The two values are close, and the bootstrap needs no formula.
To test \(H_0: \beta_1 = 0\), we divide the estimate by its standard error:
\[ T = \frac{\hat\beta_1 - 0}{\widehat{\text{SE}}(\hat\beta_1)} . \]
With the true \(\sigma\) in place of \(s\), \(T\) has a standard normal distribution under \(H_0\). We use \(s\), which varies from sample to sample. Under the normal model, \((n-2)s^2/\sigma^2\) has a chi-square distribution with \(n-2\) degrees of freedom, and it is independent of \(\hat\beta_1\). A standard normal variable divided by \(\sqrt{\chi^2_{d}/d}\) has Student’s t distribution with \(d\) degrees of freedom. So \(T \sim t_{n-2}\).
This is the same argument as for the one-sample t-test in Chapter 4. Gosset found the distribution and Fisher proved it (Chapter 1). The fit uses 2 degrees of freedom for \(\beta_0\) and \(\beta_1\), so \(n - 2\) = 29 remain.
summary(fit)
Call:
lm(formula = birthweight ~ estriol, data = estriol_df)
Residuals:
Min 1Q Median 3Q Max
-8.1200 -2.0381 -0.0381 3.3537 6.8800
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 21.5234 2.6204 8.214 4.68e-09 ***
estriol 0.6082 0.1468 4.143 0.000271 ***
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
Residual standard error: 3.821 on 29 degrees of freedom
Multiple R-squared: 0.3718, Adjusted R-squared: 0.3501
F-statistic: 17.16 on 1 and 29 DF, p-value: 0.0002712
Each row of the coefficient table has four numbers. Take the estriol row.
Estimate: the slope \(\hat\beta_1\), here 0.6082.Std. Error: its standard error from the formula above, here 0.1468.t value: the estimate divided by the standard error, here 4.143.Pr(>|t|): the probability that \(|T| \geq\) 4.143 under \(H_0\), from \(t_{n-2}\). Here it is 2.71^{-4}.We can calculate the last two by hand:
t_val <- b1 / (s / sqrt(Sxx))
c(t = t_val, p = 2 * pt(-abs(t_val), df = n - 2)) t p
4.1426562497 0.0002712299
The p-value agrees with the shuffle: chance alone rarely gives a slope this large. The (Intercept) row tests \(H_0: \beta_0 = 0\). Here it asks if a mother with zero estriol has a baby of zero weight. That question has no meaning, so we ignore this row.
The Residual standard error is \(s\) = 3.82 on 29 degrees of freedom. A typical baby is 382 g away from the line. The last three lines of the output describe the fit as a whole, and the sections on \(R^2\) and the F statistic below explain them.
A 95% confidence interval for \(\beta_1\) is \(\hat\beta_1 \pm t_{0.975,\,n-2}\,\widehat{\text{SE}}(\hat\beta_1)\).
confint(fit) 2.5 % 97.5 %
(Intercept) 16.1640740 26.8827831
estriol 0.3079268 0.9084542
quantile(boot$slope, c(0.025, 0.975)) # bootstrap percentile interval 2.5% 97.5%
0.2991450 0.9382044
The interval for the slope is 0.31 to 0.91. Each extra mg/24 h of estriol goes with between 31 g and 91 g more birthweight. The bootstrap gives 0.3 to 0.94.
The 95% is a property of the method. If we repeat the study many times and calculate an interval each time, 95% of the intervals contain the true \(\beta_1\). Our one interval either contains it or does not.
At a new value \(x_0\), the fitted value \(\hat y_0 = \hat\beta_0 + \hat\beta_1 x_0\) answers two different questions.
The first question is about the mean birthweight of all babies whose mothers have \(x_0\). Its standard error is
\[ \widehat{\text{SE}}(\hat y_0) = s\sqrt{\frac{1}{n} + \frac{(x_0 - \bar x)^2}{S_{xx}}} . \]
The second question is about the birthweight of one new baby. That baby varies around the mean with variance \(\sigma^2\). So we add 1 inside the square root:
\[ \widehat{\text{SE}}_{\text{pred}}(x_0) = s\sqrt{1 + \frac{1}{n} + \frac{(x_0 - \bar x)^2}{S_{xx}}} . \]
Both intervals are \(\hat y_0 \pm t_{0.975,\,n-2} \times \text{SE}\). Both are narrowest at \(\bar x\), as the bootstrap fan showed.
new <- data.frame(estriol = 10)
predict(fit, new, interval = "confidence") fit lwr upr
1 27.60533 25.02124 30.18942
predict(fit, new, interval = "prediction") fit lwr upr
1 27.60533 19.37414 35.83652
For a mother with 10 mg/24 h, the mean birthweight is between 2.50 kg and 3.02 kg. One baby of such a mother has a birthweight between 1.94 kg and 3.58 kg. The prediction interval includes the 2.5 kg cut-off by a wide margin.
This answers the obstetrician’s second question. Estriol tells us about the average baby. It cannot tell us if this one baby will have a low birthweight. As \(n\) increases, the confidence interval shrinks towards zero width. The prediction interval does not, because the \(1\) inside the square root stays.
grid_x <- tibble(estriol = seq(min(x), max(x), length.out = 100))
bands <- bind_cols(grid_x,
as_tibble(predict(fit, grid_x, interval = "confidence")),
as_tibble(predict(fit, grid_x, interval = "prediction")) |> rename(plwr = lwr, pupr = upr) |> dplyr::select(-fit))
ggplot(bands, aes(estriol)) +
geom_ribbon(aes(ymin = plwr, ymax = pupr), fill = "steelblue", alpha = 0.15) +
geom_ribbon(aes(ymin = lwr, ymax = upr), fill = "steelblue", alpha = 0.4) +
geom_line(aes(y = fit), colour = "firebrick", linewidth = 1) +
geom_hline(yintercept = 25, linetype = "dashed", colour = "grey50") +
geom_point(data = estriol_df, aes(y = birthweight), colour = "steelblue", size = 1.8) +
labs(x = "maternal estriol (mg/24 h)", y = "birthweight (100 g)")
Each baby’s distance from the mean birthweight has two parts. The line explains one part, and the other part is the residual:
\[ y_i - \bar y = (\hat y_i - \bar y) + (y_i - \hat y_i). \]
If we square and add over all babies, the cross term is zero. This follows from the normal equations. So
\[ \underbrace{\sum (y_i - \bar y)^2}_{\text{TSS}} = \underbrace{\sum (\hat y_i - \bar y)^2}_{\text{ESS}} + \underbrace{\sum (y_i - \hat y_i)^2}_{\text{RSS}} . \]
TSS is the total sum of squares, ESS the explained (regression) sum of squares, and RSS the residual sum of squares.
y <- estriol_df$birthweight
TSS <- sum((y - mean(y))^2)
ESS <- sum((fitted(fit) - mean(y))^2)
RSS <- sum(residuals(fit)^2)
c(TSS = TSS, ESS = ESS, RSS = RSS, ESS_plus_RSS = ESS + RSS) TSS ESS RSS ESS_plus_RSS
674.0000 250.5745 423.4255 674.0000
The coefficient of determination is the share of the total variation that the line explains:
\[ R^2 = \frac{\text{ESS}}{\text{TSS}} = 1 - \frac{\text{RSS}}{\text{TSS}} . \]
For the estriol data, \(R^2\) = 0.3718. Estriol explains 37% of the variation in birthweight. With one predictor, \(R^2\) is the square of the correlation: \(r^2\) = 0.3718.
\(R^2\) never decreases when you add a predictor, even a useless one. Least squares picks the coefficients with the smallest RSS. The bigger model can always set the new coefficient to zero and reproduce the smaller model exactly. So its smallest RSS is at most the RSS of the smaller model. TSS depends only on \(y\), so it stays the same, and \(R^2 = 1 - \text{RSS}/\text{TSS}\) cannot fall.
In practice \(R^2\) goes up by a small amount. A column of random numbers is never exactly uncorrelated with the residuals in a finite sample. Least squares uses that chance correlation, gives the column a small non-zero coefficient, and lowers RSS a little. We check this with simulated noise: we add one column of random numbers to the estriol model, 1,000 times.
set.seed(11)
rss_drop <- replicate(1000, {
noise <- rnorm(n)
RSS - sum(residuals(lm(birthweight ~ estriol + noise, data = estriol_df))^2)
})
summary(rss_drop) Min. 1st Qu. Median Mean 3rd Qu. Max.
1.300e-05 1.793e+00 7.494e+00 1.449e+01 1.979e+01 1.394e+02
RSS falls in all 1000 of 1,000 runs. The smallest drop is 0.000013, and the average drop is 14.49. On average \(R^2\) rises from 0.3718 to 0.3933, although the noise carries no information about birthweight.
The adjusted \(R^2\) divides each sum of squares by its degrees of freedom:
\[ R^2_{\text{adj}} = 1 - \frac{\text{RSS}/(n-p)}{\text{TSS}/(n-1)}, \]
where \(p\) is the number of coefficients, here 2. For the estriol data, \(R^2_{\text{adj}}\) = 0.3501. This is the value in the summary() output. Chapter 14 uses it to compare models of different sizes.
A slope with a small p-value can go with a low \(R^2\). Here 63% of the variation stays unexplained, so the prediction interval is wide.
The last line of summary() gives an F statistic. It compares the explained variation with the residual variation, each per degree of freedom:
\[ F = \frac{\text{ESS}/1}{\text{RSS}/(n-2)} . \]
anova(fit)Analysis of Variance Table
Response: birthweight
Df Sum Sq Mean Sq F value Pr(>F)
estriol 1 250.57 250.574 17.162 0.0002712 ***
Residuals 29 423.43 14.601
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
The F value is 17.16. The t value for the slope was 4.143, and its square is 17.16. With one predictor, \(F = t^2\), and the two tests give the same p-value. Chapter 14 explains the F-test for many predictors.
Many tests that you know are linear models. The two-sample t-test is the most common example.
Code a group as \(D = 0\) (control) or \(D = 1\) (treated) and fit \(Y = \beta_0 + \beta_1 D + \varepsilon\). Then \(E[Y \mid D = 0] = \beta_0\) and \(E[Y \mid D = 1] = \beta_0 + \beta_1\). So \(\beta_1\) is the difference between the two group means. Least squares gives \(\hat\beta_0 = \bar y_0\) and \(\hat\beta_1 = \bar y_1 - \bar y_0\). The t-test for \(H_0: \beta_1 = 0\) is the pooled two-sample t-test, with \(n - 2\) degrees of freedom.
We check this on real data. The birthwt data in the MASS package come from 189 births at Baystate Medical Center, Massachusetts, in 1986 (Hosmer and Lemeshow, Applied Logistic Regression, Wiley). Birthweight bwt is in grams, and smoke is 1 if the mother smoked during pregnancy.
tt <- t.test(bwt ~ smoke, data = birthwt, var.equal = TRUE)
lm_smoke <- lm(bwt ~ smoke, data = birthwt)
c(t_test = unname(tt$statistic), lm = coef(summary(lm_smoke))[2, 3]) t_test lm
2.652893 -2.652893
c(t_test = tt$p.value, lm = coef(summary(lm_smoke))[2, 4]) t_test lm
0.008666726 0.008666726
coef(lm_smoke)(Intercept) smoke
3055.6957 -283.7767
The t statistics have opposite signs, because t.test() subtracts in the other order. Their size is the same, 2.653, and the p-values are both 0.00867. The intercept 3055.7 g is the mean birthweight for non-smokers. The slope -283.8 g is the smokers’ mean (2771.9 g) minus the non-smokers’ mean (3055.7 g).
ggplot(birthwt, aes(smoke, bwt)) +
geom_jitter(width = 0.06, colour = "steelblue", alpha = 0.6, size = 1.5) +
geom_abline(intercept = coef(lm_smoke)[1], slope = coef(lm_smoke)[2], colour = "firebrick", linewidth = 1) +
scale_x_continuous(breaks = 0:1, labels = c("non-smoker\nD = 0", "smoker\nD = 1")) +
labs(x = NULL, y = "birthweight (g)")
The one-sample t-test is also a linear model. It is the model with only an intercept, lm(y ~ 1). A factor with \(k\) levels becomes \(k - 1\) indicator columns, and the F-test for all of them is the one-way ANOVA. Chapter 14 shows this.