Skip to main content

Tests as linear models

Source of the idea: Jonas Lindeløv, Common statistical tests are linear models.

Tests and the equivalent models

All the models in this course have this form:

\[g\big(E[y]\big) = X\beta\]

Three choices set the model:

  • The type of \(y\): values, ranks, signs, or counts.
  • The columns of \(X\).
  • The penalty on \(\beta\): none, ridge, or lasso.
Test (lecture) Model in R Agreement
One-sample t (L2) lm(y ~ 1) exact
Wilcoxon signed-rank (L3) lm(signed_rank(y) ~ 1) approximate, good for n ≳ 15
Sign test (L2) glm(y > m ~ 1, binomial), score test against \(p = 1/2\) approximate
Paired t (L2) lm(y2 - y1 ~ 1) exact
Two-sample t (L3–4) lm(y ~ group) exact
Mann–Whitney (L3) lm(rank(y) ~ group) approximate, good for n ≳ 15
One-way ANOVA (L6–7) lm(y ~ factor) exact
Kruskal–Wallis (not in the lectures) lm(rank(y) ~ factor) approximate
Pearson correlation (L4) lm(y ~ x) exact
Spearman correlation (not in the lectures) lm(rank(y) ~ rank(x)) exact, against cor.test(exact = FALSE)
Multiple regression (L4–6) lm(y ~ x1 + x2 + ...) same model
Ridge / lasso (L7–8) lm with a penalty on \(\beta\)
Poisson / logistic / NB (L9–10) \(X\beta\) with a different family and link
χ² test of independence (L12) glm(count ~ A * B, poisson), score test on A:B exact
χ² on a 2×2 (L11–12) glm(y ~ group, binomial), score test exact
Odds ratio exp(coef(glm(y ~ group, binomial))) exact
Mantel–Haenszel (not in the lectures) glm(y ~ stratum + group, binomial), score test approximate
McNemar (L12) glm(direction ~ 1, binomial) on discordant pairs, score test exact
Fisher’s exact (L12) logistic model with fixed margins (hypergeometric), survival::clogit exact (conditional likelihood)

Data

The data is from the Australian Health Survey. The GLM playground uses the same data. The variables are: visits to a doctor in two weeks, number of illnesses, a general health score, income (in AUD 10,000s), age, gender, chronic condition, and private insurance.

We use a random sample of 200 people. With all 5190 people, many p-values are near zero.

dv <- read.csv("data/doctorvisits.csv")
set.seed(801)
d <- dv[sample(nrow(dv), 200), ]
d$ill <- factor(pmin(d$illness, 3), labels = c("0", "1", "2", "3+"))
d$priv <- d$private == "yes"

# wilcox.test removes zero differences. lm removes the NA values.
signed_rank <- function(x) {
  x[x == 0] <- NA
  sign(x) * rank(abs(x), na.last = "keep")
}
p_coef <- function(m, term = 1) summary(m)$coefficients[term, 4]
# score (Rao) test of two nested glm models.
# For a contingency table, this is the Pearson chi-squared test.
p_score <- function(m0, m1) anova(m0, m1, test = "Rao")$`Pr(>Chi)`[2]

same <- function(test, model, tol = 1e-6) {
  out <- data.frame(classic = signif(test, 4), linear_model = signif(model, 4))
  stopifnot(abs(test - model) < tol)
  knitr::kable(out)
}

1. One sample: is the median income above $5,000?

The one-sample t-test is an lm with only an intercept. The same model on signed ranks gives an approximation of the signed-rank test.

same(t.test(d$income, mu = 0.5)$p.value,
     p_coef(lm(I(income - 0.5) ~ 1, data = d)))
classic linear_model
0.0001116 0.0001116
same(wilcox.test(d$income, mu = 0.5, exact = FALSE)$p.value,
     p_coef(lm(signed_rank(income - 0.5) ~ 1, data = d)), tol = 0.01)
classic linear_model
0.003154 0.002933

The sign test uses only the sign of each difference. It is a binomial model with an intercept, with a test against \(p = 1/2\).

above <- d$income[d$income != 0.5] > 0.5
same(binom.test(sum(above), length(above))$p.value,
     # ~ 0 sets logit(p) = 0, thus p = 1/2
     p_score(glm(above ~ 0, binomial), glm(above ~ 1, binomial)), tol = 0.05)
classic linear_model
0.2888 0.2579

binom.test gives an exact p-value. The glm score test uses the normal approximation with no continuity correction. prop.test(sum(above), length(above)) adds the correction and gives 0.2888.

2. Paired: Student’s sleep data

The data shows the extra hours of sleep of ten patients on two drugs. Cushny and Peebles measured the data in 1905. Student used the data in 1908 as the first example of his small-sample test. Fisher later changed this test into the t-test.

A paired t-test is a one-sample t-test on the differences.

diff <- with(sleep, extra[group == 2] - extra[group == 1])
same(with(sleep, t.test(extra[group == 2], extra[group == 1], paired = TRUE))$p.value,
     p_coef(lm(diff ~ 1)))
classic linear_model
0.002833 0.002833

3. Two groups: do men and women differ in income?

gender is a 0/1 column in \(X\). Its slope is the difference between the two means.

same(t.test(income ~ gender, data = d, var.equal = TRUE)$p.value,
     p_coef(lm(income ~ gender, data = d), 2))
classic linear_model
0.00428 0.00428
same(wilcox.test(income ~ gender, data = d, exact = FALSE)$p.value,
     p_coef(lm(rank(income) ~ gender, data = d), 2), tol = 0.01)
classic linear_model
0.002678 0.002469

Mann–Whitney is approximately a t-test on ranks.

The argument var.equal = TRUE is necessary. lm uses one residual variance for all groups. The default t.test in R is Welch’s test, which uses a different variance for each group. To get Welch’s test as a model, use nlme::gls with varIdent.

4. Several groups: does income differ by number of illnesses?

The model has three dummy columns, one for each group after the first group. The F-test gives the p-value for the hypothesis that all three slopes are zero.

same(oneway.test(income ~ ill, data = d, var.equal = TRUE)$p.value,
     anova(lm(income ~ ill, data = d))$`Pr(>F)`[1])
classic linear_model
0.07492 0.07492
same(kruskal.test(income ~ ill, data = d)$p.value,
     anova(lm(rank(income) ~ ill, data = d))$`Pr(>F)`[1], tol = 0.01)
classic linear_model
0.1568 0.1566

5. A continuous predictor: income and age

same(cor.test(~ age + income, data = d)$p.value,
     p_coef(lm(income ~ age, data = d), 2))
classic linear_model
0.0002096 0.0002096
same(cor.test(~ age + income, data = d, method = "spearman", exact = FALSE)$p.value,
     p_coef(lm(rank(income) ~ rank(age), data = d), 2))
classic linear_model
0.002542 0.002542

6. Penalties: ridge and lasso are lm with a penalty

When \(\lambda = 0\), glmnet gives the lm coefficients. A larger \(\lambda\) makes the coefficients smaller.

The \(\lambda\) in glmnet is not the \(\lambda\) in the closed-form ridge formula. glmnet does not apply the penalty to the intercept. It also standardizes the columns of \(X\) and divides the squared error by \(2n\).

library(glmnet)
X <- model.matrix(visits ~ illness + age + income + gender + chronic, d)[, -1]
fit_lm <- lm(visits ~ illness + age + income + gender + chronic, data = d)
fit_0  <- glmnet(X, d$visits, alpha = 0, lambda = 0, thresh = 1e-14)
round(cbind(lm = coef(fit_lm), glmnet_lambda0 = as.vector(coef(fit_0)),
            ridge = as.vector(coef(glmnet(X, d$visits, alpha = 0, lambda = 0.5))),
            lasso = as.vector(coef(glmnet(X, d$visits, alpha = 1, lambda = 0.05)))), 3)
                lm glmnet_lambda0  ridge lasso
(Intercept)  0.104          0.104  0.135 0.108
illness      0.078          0.078  0.036 0.045
age          0.001          0.001  0.001 0.000
income      -0.053         -0.053 -0.037 0.000
gendermale  -0.050         -0.050 -0.032 0.000
chronicyes  -0.053         -0.053 -0.008 0.000

7. Counts and binary outcomes: change the family

Visits are counts. Thus, keep \(X\beta\) and change the family and the link.

round(summary(glm(visits ~ illness, poisson, data = d))$coefficients, 4)
            Estimate Std. Error z value Pr(>|z|)
(Intercept)  -2.5160     0.3074 -8.1837    0e+00
illness       0.4152     0.1142  3.6372    3e-04

8. Tables: χ² and the odds ratio

tab <- table(d$gender, d$private)
tab
        
         no yes
  female 50  49
  male   54  47

The χ² test of independence is the score test of the interaction in a Poisson model of the cell counts. A logistic model of insurance on gender gives the same test.

cells <- as.data.frame(tab)
names(cells) <- c("gender", "private", "n")

same(chisq.test(tab, correct = FALSE)$p.value,
     p_score(glm(n ~ gender + private, poisson, cells),
             glm(n ~ gender * private, poisson, cells)))
classic linear_model
0.6752 0.6752
same(chisq.test(tab, correct = FALSE)$p.value,
     p_score(glm(priv ~ 1, binomial, d), glm(priv ~ gender, binomial, d)))
classic linear_model
0.6752 0.6752

The logistic slope is the log odds ratio. Thus, \(\exp(\beta) = ad / bc\):

same(tab[1, 1] * tab[2, 2] / (tab[1, 2] * tab[2, 1]),
     exp(coef(glm(priv ~ gender, binomial, d)))[[2]])
classic linear_model
0.8881 0.8881

9. Strata: Mantel–Haenszel

To adjust for a confounder, put the confounder in \(X\).

same(mantelhaen.test(table(d$gender, d$private, d$chronic), correct = FALSE)$p.value,
     p_score(glm(priv ~ chronic, binomial, d), glm(priv ~ chronic + gender, binomial, d)),
     tol = 0.01)
classic linear_model
0.6886 0.6871

10. Paired binary: McNemar

The table shows 100 patients with a symptom before and after treatment. The counts are only an example.

Only the discordant pairs give information. McNemar’s test gives the p-value for the hypothesis that the discordant pairs divide 50:50. This is the sign test again: a binomial model with only an intercept, on the discordant pairs.

paired <- matrix(c(40, 10, 25, 25), 2,
                 dimnames = list(before = c("yes", "no"), after = c("yes", "no")))
paired
      after
before yes no
   yes  40 25
   no   10 25
# discordant pairs: 25 improved (yes -> no), 10 became worse (no -> yes)
improved <- rep(c(TRUE, FALSE), c(paired["yes", "no"], paired["no", "yes"]))
same(mcnemar.test(paired, correct = FALSE)$p.value,
     p_score(glm(improved ~ 0, binomial), glm(improved ~ 1, binomial)))
classic linear_model
0.01123 0.01123

11. Fisher’s exact test: a logistic model with fixed margins

Start with the logistic model of Section 8:

\[\operatorname{logit} P(\text{insured}) = \beta_0 + \beta_1 \cdot \text{male}, \qquad \psi = e^{\beta_1} = \text{odds ratio}\]

The intercept \(\beta_0\) is a nuisance parameter. Its sufficient statistic is \(k\), the total number of insured people. When we keep \(k\) fixed, \(\beta_0\) goes out of the likelihood. The row totals are also fixed: \(m\) men and \(n\) women.

Then only one count is free: \(a\), the number of insured men. Its distribution is the noncentral hypergeometric distribution:

\[P(a \mid m, n, k;\ \psi) = \frac{\binom{m}{a}\binom{n}{k-a}\,\psi^{a}}{\sum_{u}\binom{m}{u}\binom{n}{k-u}\,\psi^{u}}\]

Two results come from this equation:

  • The value of \(\psi\) that makes \(P\) maximum is the conditional odds ratio. fisher.test gives this estimate.
  • When \(\psi = 1\), \(P\) is the hypergeometric distribution (dhyper). This is the distribution in the animation.

Fisher’s p-value is the sum of the probabilities that are not more than the probability of the observed table.

m <- sum(tab["male", ])
n <- sum(tab["female", ])
k <- sum(tab[, "yes"])
a_obs <- tab["male", "yes"]
a <- max(0, k - n):min(k, m)   # all possible values of a

# conditional likelihood of the logistic model: beta_0 is not in it
p_cond <- function(psi) {
  w <- choose(m, a) * choose(n, k - a) * psi^a
  w / sum(w)
}
ft <- fisher.test(tab)

# 1. the conditional MLE of psi is the odds ratio from fisher.test
b_hat <- optimize(function(b) log(p_cond(exp(b))[a == a_obs]),
                  c(-5, 5), maximum = TRUE, tol = 1e-10)$maximum
same(ft$estimate[[1]], exp(b_hat), tol = 1e-4)
classic linear_model
0.8887 0.8887
# 2. with psi = 1, the distribution is dhyper
p0 <- p_cond(1)
same(dhyper(a_obs, m, n, k), p0[a == a_obs])
classic linear_model
0.1031 0.1031
# 3. the p-value: sum over the tables that are not more probable than the observed table
in_p <- p0 <= p0[a == a_obs] * (1 + 1e-7)
same(ft$p.value, sum(p0[in_p]))
classic linear_model
0.7772 0.7772

survival::clogit fits the same conditional likelihood. The full table is one stratum.

library(survival)
d$all <- 1
cl <- clogit(priv ~ gender + strata(all), data = d, method = "exact")
same(ft$estimate[[1]], exp(coef(cl))[[1]], tol = 1e-4)
classic linear_model
0.8887 0.8887

The plot shows the distribution of \(a\) when \(\psi = 1\). The black bar is the observed table. The p-value is the sum of the black bar and the red bars.

show <- p0 > 1e-4
barplot(p0[show], names.arg = a[show], border = NA, space = 0.1, ylim = c(0, 1.1 * max(p0)),
        col = ifelse(a[show] == a_obs, "black", ifelse(in_p[show], "firebrick", "grey80")),
        xlab = "a = number of insured men (margins fixed)", ylab = "P(a) when psi = 1")

The glm uses the full likelihood, with \(\beta_0\) in it. It gives the unconditional odds ratio \(ad/bc\) and a large-sample p-value.

m_glm <- glm(priv ~ gender, binomial, d)
knitr::kable(data.frame(
  method = c("Fisher (conditional, exact)", "logistic glm (Wald)"),
  odds_ratio = signif(c(ft$estimate, exp(coef(m_glm))[[2]]), 4),
  p = signif(c(ft$p.value, p_coef(m_glm, 2)), 4)))
method odds_ratio p
odds ratio Fisher (conditional, exact) 0.8887 0.7772
logistic glm (Wald) 0.8881 0.6753

With 200 people, the two odds ratios are the same to three digits. Both p-values are much larger than 0.05. With small expected counts, as in the trial in Lecture 12, the two results are different. In that case, use Fisher’s test.

Where from here

Each of the next methods adds one part to this model.

  • Mixed models. A paired t-test is a model with a random intercept for each patient. lme4::lmer(extra ~ group + (1 | ID), sleep) gives the same t as Section 2, if the estimate of the patient variance is more than zero. The same model works for many visits for each patient, and for patients in hospitals.
  • Bayesian regression. The ridge estimate is the posterior mode with a Gaussian prior on the slopes. The lasso estimate is the posterior mode with a Laplace prior.
  • Survival analysis. Cox regression puts \(X\beta\) on the log hazard.
  • Causal inference. Mantel–Haenszel and Simpson’s paradox were the first step. The columns that go in \(X\) are a causal decision, not a statistical decision.
same(with(sleep, t.test(extra[group == 2], extra[group == 1], paired = TRUE))$statistic[[1]],
     summary(lme4::lmer(extra ~ group + (1 | ID), data = sleep))$coefficients[2, 3])
classic linear_model
4.062 4.062