Skip to main content

7  The permutation test

The rank-sum test of Chapter 6 found its null distribution with a shuffle of the group labels. The permutation test makes this idea general. If the null hypothesis is true, the labels carry no information, and every relabelling of the subjects is equally likely. The relabellings give the null distribution of any statistic, with no assumption about its shape. Fisher used the same argument in 1935 for the lady tasting tea (Chapter 1, Chapter 9).

7.1 The problem

Rosner describes a pilot study of vitamin E as a possible preventive agent for Alzheimer’s disease (Fundamentals of Biostatistics). Subjects aged 65 or more are randomised to vitamin E at 400 IU/day (group 1) or to placebo (group 2). Before the trial starts, we must check that the two groups have a similar total intake of vitamin E, from food and supplements. The baseline intakes in IU/day are below.

g1 <- c(7.5, 12.6, 3.8, 20.2, 6.8, 403.3, 2.9, 7.2, 10.5, 205.4)   # vitamin E
g2 <- c(8.2, 13.3, 102.0, 12.7, 6.3, 4.8, 19.5, 8.3, 407.1, 10.2)  # placebo
m <- length(g1); n <- length(g2); N <- m + n
c(mean_1 = mean(g1), mean_2 = mean(g2), median_1 = median(g1), median_2 = median(g2))
  mean_1   mean_2 median_1 median_2 
   68.02    59.24     9.00    11.45 

There are 20 subjects, 10 in each group. The mean intake is 68 IU/day in group 1 and 59.2 IU/day in group 2. The medians are 9 and 11.45. There are 4 intakes above 100 IU/day, and these values decide the means (Figure 7.1).

Show code
intake <- tibble(group = rep(c("1 (vitamin E)", "2 (placebo)"), c(m, n)), iu = c(g1, g2))
ggplot(intake, aes(iu, group, colour = group)) +
  geom_point(size = 3, alpha = 0.7) +
  scale_colour_manual(values = c("steelblue", "firebrick"), guide = "none") +
  labs(x = "baseline vitamin E intake (IU/day)", y = "group")
Figure 7.1: Baseline vitamin E intake of the 20 subjects, by group. The 4 intakes above 100 IU/day lie far to the right of the others.

Did the two groups have the same vitamin E intake at baseline?

7.2 Intuitive solution

7.2.1 A toy example

We start with 6 subjects, 3 in each group. Group 1 has the scores 10, 20 and 36, and group 2 has the scores 5, 9 and 11.

toy <- tibble(id = 1:6, group = rep(1:2, each = 3), score = c(10, 20, 36, 5, 9, 11)) |>
  mutate(rank = rank(score))
toy
# A tibble: 6 × 4
     id group score  rank
  <int> <int> <dbl> <dbl>
1     1     1    10     3
2     2     1    20     5
3     3     1    36     6
4     4     2     5     1
5     5     2     9     2
6     6     2    11     4
R1_toy <- sum(toy$rank[toy$group == 1])
R1_toy
[1] 14

Group 1 has the ranks 3, 5, 6, so its rank sum is \(R_1 =\) 14.

Is a rank sum of 14 unusually large?

7.2.2 Shuffle the labels

Suppose that the treatment does nothing. Then the labels “group 1” and “group 2” are cards that we handed out at random. Any 3 of the 6 subjects can hold the group 1 cards. There are \(\binom{6}{3} =\) 20 ways to hand out the cards, and under \(H_0\) all of them are equally likely. We calculate \(R_1\) for each one.

R1_all <- combn(6, 3, \(i) sum(toy$rank[i]))           # R1 for each choice of group 1
table(R1_all)
R1_all
 6  7  8  9 10 11 12 13 14 15 
 1  1  2  3  3  3  3  2  1  1 
Show code
tibble(R1 = R1_all) |>
  count(R1) |>
  mutate(extreme = abs(R1 - centre_toy) >= abs(R1_toy - centre_toy)) |>
  ggplot(aes(factor(R1), n, fill = extreme)) +
  geom_col(width = 0.7) +
  scale_fill_manual(values = c(`FALSE` = "steelblue", `TRUE` = "firebrick"), guide = "none") +
  labs(x = "rank sum of group 1", y = "number of relabellings")
Figure 7.2: The rank sum of group 1 for each of the 20 ways to choose 3 of the 6 subjects as group 1. The red bars are the sums at least as far from the centre (10.5) as the observed 14.

Each relabelling has the probability 1/20 under \(H_0\). A rank sum of 14 or more occurs in 2 of the 20 relabellings, so the one-sided p-value is 0.10. The mirror tail, \(R_1 \le\) 7, holds 2 more relabellings. The two-sided p-value is 0.20.

With 3 subjects in each group, the smallest possible two-sided p-value is 2/20 = 0.10. No result can reach 0.05, however large the effect. A study this small cannot give a significant result.

7.3 Formal solution

7.3.1 Hypotheses

Two independent samples, X of size \(m\) and Y of size \(n\), have \(N = m + n\) values in total. The null hypothesis says that both samples come from the same distribution. The alternative says that one distribution is a shift of the other:

\[ H_0: F_X = F_Y, \qquad H_1: F_Y(x) = F_X(x - \delta) \text{ for some } \delta \ne 0. \]

The test needs one assumption: under \(H_0\), the labels X and Y are exchangeable. This means that any \(m\) of the \(N\) subjects can be the X sample. In a randomised trial, the design makes this true, because the trial assigned the labels at random.

7.3.2 The permutation distribution

Rank all \(N\) values together, and let \(R_{1,\text{obs}}\) be the rank sum of the X sample. There are \(K = \binom{N}{m}\) relabellings, and each one gives a value of \(R_1\). These \(K\) values form the permutation distribution. The two-sided p-value is

\[ p = 2 \times \min\left[\Pr(R_1^{\text{perm}} \le R_{1,\text{obs}}),\ \Pr(R_1^{\text{perm}} \ge R_{1,\text{obs}}),\ 0.5\right]. \]

The 0.5 in the formula keeps the p-value at or below 1. For the vitamin E data, we can list all the relabellings.

r <- rank(c(g1, g2))
R1_obs <- sum(r[1:m])
K <- choose(N, m)
R1_perm <- combn(N, m, \(i) sum(r[i]))                 # R1 for every relabelling
p_exact <- 2 * min(mean(R1_perm <= R1_obs), mean(R1_perm >= R1_obs), 0.5)
centre <- m * (N + 1) / 2                              # mean of R1 under H0
c(R1_obs = R1_obs, expected = centre, K = K, p = p_exact)
      R1_obs     expected            K            p 
9.700000e+01 1.050000e+02 1.847560e+05 5.787417e-01 

There are 184,756 relabellings. The observed rank sum is 97, and its expected value under \(H_0\) is \(m(N + 1)/2 =\) 105. The exact two-sided p-value is 0.579.

7.3.3 Monte Carlo shuffles

The number of relabellings grows fast with the sample size. With 25 subjects in each group, \(K =\) 1.3 \(\times 10^{14}\), too many to list. We then shuffle the labels at random \(B\) times and calculate \(R_1\) after each shuffle. The proportion of shuffles at least as far from the centre as the data estimates the two-sided p-value.

set.seed(2026)
B <- 10000
R1_mc <- replicate(B, sum(sample(r)[1:m]))             # shuffle the labels, B times
p_mc <- mean(abs(R1_mc - centre) >= abs(R1_obs - centre))
se_mc <- sqrt(p_mc * (1 - p_mc) / B)
c(p_monte_carlo = p_mc, se = se_mc, p_exact = p_exact)
p_monte_carlo            se       p_exact 
  0.575600000   0.004942516   0.578741692 

The estimate is a proportion from \(B\) shuffles. Its standard error (SE) is \(\sqrt{p(1 - p)/B}\). With \(B =\) 10,000, the SE is 0.0022 at \(p = 0.05\). For the vitamin E data, the Monte Carlo p-value is 0.576, with an SE of 0.005. It is within 0.6 SE of the exact value. Section 7.5 derives the SE.

Show code
tibble(R1 = R1_mc) |>
  mutate(extreme = abs(R1 - centre) >= abs(R1_obs - centre)) |>
  ggplot(aes(R1, fill = extreme)) +
  geom_bar(width = 0.8) +
  geom_vline(xintercept = R1_obs, linetype = "dashed", colour = "grey40") +
  scale_fill_manual(values = c(`FALSE` = "steelblue", `TRUE` = "firebrick"), guide = "none") +
  labs(x = "rank sum of group 1 after a shuffle", y = "number of shuffles")
Figure 7.3: The rank sum of group 1 after 10,000 random shuffles of the vitamin E labels. The red bars are the sums at least as far from the centre (105) as the observed 97 (dashed line).

The observed rank sum lies in the middle of the shuffled values. Most shuffles give a result at least as extreme as the data.

7.3.4 The test in R

wt <- wilcox.test(g1, g2)
wt

    Wilcoxon rank sum exact test

data:  g1 and g2
W = 42, p-value = 0.5787
alternative hypothesis: true location shift is not equal to 0
  • Wilcoxon rank sum exact test: R uses the exact permutation distribution of the rank sum. Both samples have fewer than 50 values, and there are no ties.
  • W: 42. This is \(U_1 = R_1 - m(m + 1)/2 =\) 97 \(-\) 55 (Chapter 6).
  • p-value: 0.5787. It is the exact value from our list of 184,756 relabellings.
  • alternative hypothesis: true location shift is not equal to 0: the two-sided \(H_1\) above.

The data give no evidence of a difference in baseline intake. The randomisation gave two balanced groups.

Ranks use only the order of the values. The intake of 403.3 IU/day gets the rank 19 of 20. Its size, 39 times the median intake, has no effect on the test.

7.4 Other statistics

The shuffle works for any statistic. Chapter 8 shuffled the case and control labels for a difference in proportions. For a difference in means, we shuffle the raw intakes.

x <- c(g1, g2)
d_obs <- mean(g1) - mean(g2)
set.seed(2026)
d_mc <- replicate(B, {
  s <- sample(x)                                       # shuffle the labels
  mean(s[1:m]) - mean(s[-(1:m)])
})
p_mean <- mean(abs(d_mc) >= abs(d_obs))
c(difference = d_obs, p = p_mean)
difference          p 
    8.7800     0.9362 

The difference in means is 8.78 IU/day, and the permutation p-value is 0.936. Each shuffle moves the 4 large intakes between the groups, so the shuffled differences have a wide spread. The test is still valid, because the shuffle makes no assumption of normality. The large values make the mean a noisy statistic, and the rank sum ignores their size.

7.5 The precision of Monte Carlo p-values

7.5.1 Each shuffle is a Bernoulli trial

Let \(p\) be the exact permutation p-value. It is the proportion of all \(K\) relabellings that are at least as extreme as the data. A random shuffle picks one of the \(K\) relabellings, each with the probability \(1/K\). Let \(I_j = 1\) if shuffle \(j\) is at least as extreme as the data, and \(I_j = 0\) if not. Then \(\Pr(I_j = 1) = p\), so each \(I_j\) is a Bernoulli trial.

The \(B\) shuffles are independent, so the count of extreme shuffles \(b = \sum_j I_j\) is binomial:

\[ b \sim \text{Binomial}(B, p), \qquad \hat p = \frac{b}{B}. \]

7.5.2 The standard error

A Bernoulli trial has the mean \(p\) and the variance \(p(1 - p)\). The mean of a sum is the sum of the means. For independent trials, the variance of a sum is the sum of the variances. So

\[ E(\hat p) = \frac{1}{B} \sum_{j=1}^{B} E(I_j) = p, \qquad \operatorname{Var}(\hat p) = \frac{1}{B^2} \sum_{j=1}^{B} \operatorname{Var}(I_j) = \frac{p(1 - p)}{B}. \]

The estimate has no bias, and its SE is \(\sqrt{p(1 - p)/B}\). The true \(p\) is unknown, so we put \(\hat p\) in its place. For a large \(B\), the central limit theorem makes \(\hat p\) close to normal. Then \(\hat p \pm 1.96\,\text{SE}\) is an approximate 95% confidence interval for the exact p-value.

c(estimate = p_mc, lower = p_mc - 1.96 * se_mc, upper = p_mc + 1.96 * se_mc, exact = p_exact)
 estimate     lower     upper     exact 
0.5756000 0.5659127 0.5852873 0.5787417 

For the vitamin E data, the interval is 0.566 to 0.585, and it contains the exact value 0.579. The SE falls as \(1/\sqrt{B}\). Ten times more shuffles make the SE \(\sqrt{10} =\) 3.16 times smaller.

7.5.3 The number of shuffles

Suppose that we want a 95% interval with the half-width \(h\). We solve \(1.96 \sqrt{p(1 - p)/B} = h\) for \(B\):

\[ B = \frac{1.96^2\, p(1 - p)}{h^2}. \]

h <- 0.005
B_05 <- ceiling(1.96^2 * 0.05 * 0.95 / h^2)            # at p = 0.05
B_any <- ceiling(1.96^2 / (4 * h^2))                   # at p = 1/2, the worst case
c(B_05 = B_05, B_any = B_any)
 B_05 B_any 
 7300 38416 

Near the 5% threshold, \(h =\) 0.005 needs \(B =\) 7,300 shuffles. The product \(p(1 - p)\) is largest at \(p = 1/2\), where it is \(1/4\). So \(B = 1.96^2 / (4h^2) =\) 38,416 shuffles give this precision for every \(p\).

7.5.4 Two estimates of a two-sided p-value

The formal solution gave the form \(2 \times \min[\dots]\) for the two-sided p-value. The Monte Carlo code above uses the distance from the centre. This puts both tails into one Bernoulli trial, with the probability \(p\). The form \(2 \times \min[\dots]\) doubles the estimate for one tail. Each tail has the probability \(p/2\), so

\[ \operatorname{Var}(2 \hat p_{\text{tail}}) = 4 \cdot \frac{(p/2)(1 - p/2)}{B} = \frac{p(2 - p)}{B}. \]

The null distribution of the rank sum is symmetric about its centre, so both forms estimate the same \(p\). The SE of the doubled form is larger by the factor \(\sqrt{(2 - p)/(1 - p)}\). For the vitamin E data, this factor is 1.84.

7.5.5 A simulation of the Monte Carlo error

We repeat the Monte Carlo test many times for each of three values of \(B\). Each repeat gives both estimates from the same shuffles. The spread of the repeats is the true Monte Carlo error, and we compare it with the formulae.

set.seed(1)
reps <- 100
B_values <- c(100, 1000, 10000)
mc_runs <- map_dfr(B_values, \(n_shuffle) map_dfr(1:reps, \(i) {
  R1 <- replicate(n_shuffle, sum(sample(r, m)))        # random relabellings
  tibble(B = n_shuffle,
         distance = mean(abs(R1 - centre) >= abs(R1_obs - centre)),
         doubled  = 2 * min(mean(R1 <= R1_obs), mean(R1 >= R1_obs), 0.5))
}))
mc_runs |>
  group_by(B) |>
  summarise(sd_distance = sd(distance), se_distance = sqrt(p_exact * (1 - p_exact) / first(B)),
            sd_doubled = sd(doubled), se_doubled = sqrt(p_exact * (2 - p_exact) / first(B)))
# A tibble: 3 × 5
      B sd_distance se_distance sd_doubled se_doubled
  <dbl>       <dbl>       <dbl>      <dbl>      <dbl>
1   100     0.0504      0.0494     0.0855     0.0907 
2  1000     0.0154      0.0156     0.0276     0.0287 
3 10000     0.00509     0.00494    0.00888    0.00907

Each observed SD (sd_) is close to its formula (se_). At \(B =\) 10,000, the SD of the distance estimate is 0.0051, and the formula gives 0.0049. The formula predicts that each tenfold increase in \(B\) makes the SD \(\sqrt{10}\) times smaller, and the observed SDs follow it. Over all 300 repeats, 95.3% of the distance estimates lie within 1.96 SE of the exact p-value.

Show code
ggplot(mc_runs, aes(factor(B), distance)) +
  geom_jitter(width = 0.15, height = 0, size = 1, alpha = 0.4, colour = "steelblue") +
  geom_hline(yintercept = p_exact, colour = "grey40") +
  geom_errorbar(data = bands, aes(x = factor(B), ymin = p_exact - 1.96 * se, ymax = p_exact + 1.96 * se),
                inherit.aes = FALSE, width = 0.4, colour = "firebrick", linewidth = 1) +
  labs(x = "number of shuffles B", y = "Monte Carlo p-value")
Figure 7.4: Monte Carlo estimates of the two-sided p-value for the vitamin E data, from the distance to the centre, 100 repeats for each number of shuffles B. The grey line is the exact p-value (0.579). The red bars are the exact p-value plus or minus 1.96 SE.

7.5.6 A p-value of zero

If no shuffle is as extreme as the data, then \(b = 0\) and \(\hat p = 0\). A p-value of 0 is wrong, because the observed labelling is itself one of the relabellings. Phipson and Smyth (Statistical Applications in Genetics and Molecular Biology, 2010) add the observed labelling to the count:

\[ \hat p = \frac{b + 1}{B + 1}. \]

Under \(H_0\), the observed statistic and the \(B\) shuffled statistics are exchangeable. Without ties, the rank of the observed value among the \(B + 1\) values is then uniform on \(1, \dots, B + 1\). Rank 1 is the most extreme value, so the rank is \(b + 1\). Thus \(\Pr(b + 1 \le k) = k/(B + 1)\) for each \(k\). A test that rejects when \((b + 1)/(B + 1) \le \alpha\) then rejects a true \(H_0\) with a probability of at most \(\alpha\). With ties, the probability is smaller.

The smallest possible value is \(1/(B + 1)\). With \(B =\) 10,000, it is 1/10,001. In Chapter 8, no shuffle reached the observed gap. This rule then gives the smallest possible value, and the report “p is less than \(1/B\)” agrees with it.

7.6 Summary

  • The permutation test builds the null distribution of a statistic from the data, with all the relabellings of the subjects.
  • Exchangeability of the labels under the null hypothesis is the only assumption, and randomisation makes it true.
  • Monte Carlo shuffles estimate the p-value when there are too many relabellings to list. The count of extreme shuffles is binomial, so the SE of the estimate is \(\sqrt{p(1 - p)/B}\).
  • Sample size limits the smallest possible p-value. With 3 subjects per group, the two-sided p-value cannot go below 0.10.