Skip to main content

5  The Wilcoxon signed-rank test

The sign test uses only the direction of each paired difference. The signed-rank test of Frank Wilcoxon (1945) also uses the size of each difference, but through its rank. Chapter 1 covers the story of the test.

5.1 The problem

Two ointments, A and B, are tested for protection from sunburn. Each person gets ointment A on one arm and ointment B on the other arm. After exposure to sunlight, a doctor scores the burn on each arm on a 20-point scale. A score of 1 is no burn and a score of 20 is the worst burn.

For each person \(i\), the difference is \(d_i = a_i - b_i\), the burn score with A minus the burn score with B. A positive \(d_i\) means that B gave less burn.

d <- c(13, 20, 12, -3, 4, -2, 9, -1, 11)   # burn with A minus burn with B
length(d); sum(d > 0); sum(d < 0)
[1] 9
[1] 6
[1] 3

Of the 9 differences, 6 are positive. The positive differences are also large, and the negative differences are small. The sign test sees only 6 against 3 and ignores the sizes. The signed-rank test uses the sizes too.

Does the burn score depend on the ointment?

5.2 Intuitive solution

Wilcoxon replaced each difference by a signed rank:

  1. Take the absolute value of each difference.
  2. Rank the absolute values from smallest to largest.
  3. Give each rank the sign of its difference.
sunburn <- tibble(person = 1:9, d = d, abs_d = abs(d),
                  rank = rank(abs(d)), signed_rank = sign(d) * rank(abs(d)))
sunburn
# A tibble: 9 × 5
  person     d abs_d  rank signed_rank
   <int> <dbl> <dbl> <dbl>       <dbl>
1      1    13    13     8           8
2      2    20    20     9           9
3      3    12    12     7           7
4      4    -3     3     3          -3
5      5     4     4     4           4
6      6    -2     2     2          -2
7      7     9     9     5           5
8      8    -1     1     1          -1
9      9    11    11     6           6
W_plus  <- sum(sunburn$rank[d > 0])
W_minus <- sum(sunburn$rank[d < 0])
c(W_plus = W_plus, W_minus = W_minus, total = W_plus + W_minus)
 W_plus W_minus   total 
     39       6      45 

The positive ranks add to \(W^+ = 39\) and the negative ranks add to \(W^- = 6\). The two sums always add to \(1 + 2 + \dots + n = n(n+1)/2\), here 45.

Show code
sunburn |>
  mutate(direction = if_else(d > 0, "B better (d > 0)", "A better (d < 0)")) |>
  ggplot(aes(reorder(factor(person), abs_d), d, fill = direction)) +
  geom_col(width = 0.7) +
  geom_hline(yintercept = 0, colour = "grey50") +
  geom_text(aes(label = signed_rank, vjust = if_else(d > 0, -0.3, 1.3)), size = 3.5) +
  scale_fill_manual(values = c("B better (d > 0)" = "steelblue", "A better (d < 0)" = "firebrick")) +
  scale_y_continuous(expand = expansion(mult = 0.12)) +
  labs(x = "person (sorted by |d|)", y = "difference d", fill = NULL) +
  theme(legend.position = "top")
Figure 5.1: The nine sunburn differences (burn with A minus burn with B), sorted by size. The label on each bar is its signed rank. The large differences are all positive.

Now suppose that the two ointments are equally good. Then a difference of a given size is equally likely to be positive or negative. Each rank gets a “+” or a “−” sign by the toss of a fair coin.

We can simulate this. We flip a coin for each of the ranks 1 to 9, add the ranks that get “+”, and repeat 10,000 times.

set.seed(42)
n <- length(d)
flips <- replicate(10000, sum((1:n)[sample(c(TRUE, FALSE), n, replace = TRUE)]))
mean(flips >= W_plus | flips <= W_minus)
[1] 0.0575
Show code
tibble(W = flips) |>
  mutate(extreme = W >= W_plus | W <= W_minus) |>
  ggplot(aes(W, fill = extreme)) +
  geom_bar(width = 0.8) +
  scale_fill_manual(values = c(`FALSE` = "steelblue", `TRUE` = "firebrick"), guide = "none") +
  geom_vline(xintercept = W_plus, linetype = "dashed", colour = "grey40") +
  annotate("text", x = W_plus, y = Inf, label = "observed W+", vjust = 1.5, hjust = 1.05, colour = "grey30") +
  labs(x = expression(W^"+" ~ "under random signs"), y = "count")
Figure 5.2: The sum of the positive ranks in 10,000 random sign patterns for nine ranks. The red bars are the sums at least as far from the centre as the observed value.

The simulated sums centre on 22.5 and are symmetric. A sum of 39 or more, or 6 or less, occurs in 5.8% of the random sign patterns.

With nine ranks there are \(2^9 = 512\) sign patterns, so we can also list all of them and get the exact answer.

patterns <- expand.grid(rep(list(c(FALSE, TRUE)), n))   # all 512 sign patterns
W_all <- as.matrix(patterns) %*% (1:n)
c(extreme = sum(W_all >= W_plus | W_all <= W_minus), patterns = nrow(patterns))
 extreme patterns 
      28      512 
mean(W_all >= W_plus | W_all <= W_minus)
[1] 0.0546875

In all, 28 of the 512 patterns are as extreme as the data. The exact two-sided p-value is 0.0547. The evidence against “no difference” is moderate, and it does not reach the 5% level.

5.3 Formal solution

5.3.1 Assumptions and hypotheses

The test needs paired data. The differences \(d_1, \dots, d_n\) must be independent of each other. The differences must come from a continuous distribution.

\(H_0\): the distribution of the differences is symmetric about 0.
\(H_1\): the distribution is not symmetric about 0 (it is shifted).

Symmetry is the assumption that makes each sign a fair coin. It does not require a normal distribution.

5.3.2 The procedure

  1. Calculate \(d_i = a_i - b_i\) for each pair. Remove the differences that are zero.
  2. Rank \(|d_i|\) from smallest (rank 1) to largest (rank \(n\)).
  3. Give each rank the sign of \(d_i\).
  4. Add the positive ranks to get \(W^+\), and add the absolute values of the negative ranks to get \(W^-\).
  5. For a printed table, use \(W_s = \max(W^+, W^-)\). R reports \(V = W^+\).

Under \(H_0\), each rank \(i\) adds \(i\) to \(W^+\) with probability ½. This gives

\[E(W^+) = \frac{n(n+1)}{4}, \qquad \mathrm{Var}(W^+) = \frac{n(n+1)(2n+1)}{24}.\]

For small \(n\), the exact distribution comes from the \(2^n\) sign patterns, as in the intuitive solution. R has this distribution in dsignrank() and psignrank(). Printed tables give the critical value of \(W_s\) for each \(n\).

crit <- n * (n + 1) / 2 - qsignrank(0.025, n) + 1   # smallest W_s with two-sided p <= 0.05
c(critical_value = crit, exact_p_at_critical = 2 * psignrank(n * (n + 1) / 2 - crit, n))
     critical_value exact_p_at_critical 
         40.0000000           0.0390625 

For \(n = 9\) the two-sided 5% critical value is 40. Our \(W_s = 39\) is below it, so we do not reject \(H_0\) at the 5% level.

5.3.3 The test in R

wilcox.test(d, conf.int = TRUE)

    Wilcoxon signed rank exact test

data:  d
V = 39, p-value = 0.05469
alternative hypothesis: true location is not equal to 0
96.1 percent confidence interval:
 -1 13
sample estimates:
(pseudo)median 
           6.5 

Read the output line by line:

  • Wilcoxon signed rank exact test: R uses the exact distribution. It does this by default for fewer than 50 differences.
  • V = 39: \(V\) is \(W^+\), the sum of the positive ranks.
  • p-value = 0.05469: this is the exact p-value. It is 28/512, the same as our count of sign patterns.
  • 96.1 percent confidence interval: -1 13: an interval for the centre of the differences. With 9 values, R cannot get exactly 95%, so it gives the smallest achievable level above 95%.
  • (pseudo)median 6.5: the Hodges–Lehmann estimate of the centre. The section on what to report explains it.

If you have the two columns \(a\) and \(b\), wilcox.test(a, b, paired = TRUE) gives the same result as wilcox.test(a - b).

5.3.4 The normal approximation

For larger \(n\), \(W^+\) has an approximately normal distribution. The test statistic subtracts the mean, takes ½ off the distance for continuity, and divides by the standard deviation:

\[T = \frac{\left|W^+ - \frac{n(n+1)}{4}\right| - \frac{1}{2}}{\sqrt{\frac{n(n+1)(2n+1)}{24}}}, \qquad p = 2\,[1 - \Phi(T)].\]

The ½ is a continuity correction: \(W^+\) takes only whole-number values while the normal curve is continuous.

E_W  <- n * (n + 1) / 4
SD_W <- sqrt(n * (n + 1) * (2 * n + 1) / 24)
T_stat <- (abs(W_plus - E_W) - 0.5) / SD_W
c(T = T_stat, p_normal = 2 * (1 - pnorm(T_stat)))
         T   p_normal 
1.89551641 0.05802402 
wilcox.test(d, exact = FALSE)$p.value
[1] 0.05802402

Even at \(n = 9\) the approximate p-value (0.058) is close to the exact value (0.055).

Show code
tibble(w = 0:(n * (n + 1) / 2), p = dsignrank(w, n)) |>
  ggplot(aes(w, p)) +
  geom_col(fill = "steelblue", width = 0.8) +
  stat_function(fun = \(x) dnorm(x, E_W, SD_W), colour = "firebrick", linewidth = 1) +
  geom_vline(xintercept = W_plus, linetype = "dashed", colour = "grey40") +
  labs(x = expression(W^"+"), y = "probability")
Figure 5.3: The exact null distribution of W+ for n = 9 (bars) and the normal approximation with the same mean and standard deviation (red curve).

5.4 Zeros and ties

Real scores often have zeros and ties. The standard rules handle them as follows.

  • A difference of zero has no sign. Remove it and reduce \(n\).
  • Tied absolute values get the average of their ranks (midranks).
  • With ties, the variance becomes smaller. If \(t_j\) values share the \(j\)th tied rank, subtract \(\sum_j (t_j^3 - t_j)/48\) from the variance.

The p-value from tied data is approximate, because the exact tables assume the ranks \(1, 2, \dots, n\).

The hands-on session of the course used the R sleep data. These are the data of Cushny and Peebles (1905) that Student analysed in 1908 (Chapter 1). Ten patients took two sleep drugs, and the outcome is the hours of extra sleep.

drug1 <- sleep$extra[sleep$group == 1]
drug2 <- sleep$extra[sleep$group == 2]
d_sleep <- drug2 - drug1
d_sleep
 [1] 1.2 2.4 1.3 1.3 0.0 1.0 1.8 0.8 4.6 1.4

One difference is zero, and two differences are both 1.3. We remove the zero, rank the rest, and apply the tie correction.

d_nz <- d_sleep[d_sleep != 0]
n_s  <- length(d_nz)
r_s  <- rank(abs(d_nz))
t_j  <- table(r_s)                         # sizes of the tied groups
V_s  <- sum(r_s[d_nz > 0])
var_s <- n_s * (n_s + 1) * (2 * n_s + 1) / 24 - sum(t_j^3 - t_j) / 48
T_s  <- (abs(V_s - n_s * (n_s + 1) / 4) - 0.5) / sqrt(var_s)
c(n = n_s, V = V_s, T = T_s, p = 2 * (1 - pnorm(T_s)))
           n            V            T            p 
 9.000000000 45.000000000  2.608624334  0.009090698 
wilcox.test(drug2, drug1, paired = TRUE, exact = FALSE)

    Wilcoxon signed rank test with continuity correction

data:  drug2 and drug1
V = 45, p-value = 0.009091
alternative hypothesis: true location shift is not equal to 0

All 9 non-zero differences are positive, so \(V = 45\), the largest possible value. The hand calculation and R agree: \(p = 0.00909\).

We used exact = FALSE to get the textbook normal approximation. Recent versions of R (this book uses 4.6.2) give an exact p-value by default, even with ties and zeros. That exact version keeps the zero in the ranking (Pratt’s method), so its \(V\) and p-value differ from the textbook values. Older versions of R used the normal approximation with a warning. A report must state which version of the test it used.

wilcox.test(drug2, drug1, paired = TRUE)[c("method", "statistic", "p.value")]
$method
[1] "Wilcoxon signed rank exact test"

$statistic
 V 
54 

$p.value
[1] 0.00390625

5.5 One extreme value

Ranks keep the order of the data and drop the distances. This loss of information becomes an advantage when one value is extreme.

The nine differences below are made-up numbers for illustration. Every patient improved. Eight improved by about 1 unit, and one improved by 25 units.

d_out <- c(0.7, 0.8, 0.9, 0.95, 1.05, 1.1, 1.3, 1.5, 25)   # illustrative, not real data
c(mean = mean(d_out), sd = sd(d_out))
    mean       sd 
3.700000 7.991284 
t.test(d_out)$p.value
[1] 0.2022711
wilcox.test(d_out)$p.value
[1] 0.00390625

The large value moves the mean to 3.7, but it moves the standard deviation even more, to 8.0. The t statistic is the mean divided by its standard error, so it becomes small. The t-test gives \(p = 0.20\), although every patient improved.

The signed-rank test sees nine positive signs. The patient with 25 units has rank 9, and a rank cannot be larger than \(n\). \(W^+ = 45\) is the most extreme value possible, and \(p = 2/2^9 = 0.0039\).

Show code
p_raw <- ggplot(tibble(d = d_out), aes(d, 0)) +
  geom_vline(xintercept = 0, colour = "grey60") +
  geom_point(colour = "steelblue", size = 2.5) +
  annotate("point", x = mean(d_out), y = 0, colour = "firebrick", shape = 4, size = 4, stroke = 1.3) +
  annotate("text", x = mean(d_out), y = 0.5, label = "mean", colour = "firebrick") +
  scale_y_continuous(limits = c(-1, 1), breaks = NULL) +
  labs(x = "improvement d", y = NULL)
p_rank <- ggplot(tibble(r = rank(abs(d_out))), aes(r, 0)) +
  geom_point(colour = "steelblue", size = 2.5) +
  scale_x_continuous(breaks = 1:9) +
  scale_y_continuous(limits = c(-1, 1), breaks = NULL) +
  labs(x = "signed rank", y = NULL)
p_raw + p_rank
Figure 5.4: Illustrative data: nine improvements, one of them very large. On the original scale (left), the large value dominates the mean and standard deviation. On the rank scale (right), it is only rank 9.

Ranks lose some efficiency. If the data are normal, the signed-rank test has an asymptotic relative efficiency of \(3/\pi = 0.955\) compared with the t-test. It needs about 5% more patients for the same power. The sunburn data show this cost. The one-sample t-test on the same nine differences gives \(p = 0.029\), smaller than the signed-rank \(p\) of 0.055. For heavy tails or outliers, the signed-rank test can be much more efficient than the t-test.

5.6 The pseudo-median and what to report

The null hypothesis is symmetry about zero. The test is a test of the median only if the differences are symmetric. Otherwise it tests the pseudo-median: the median of the averages \((d_i + d_j)/2\) over all pairs \(i \le j\).

The sample version of the pseudo-median is the Hodges–Lehmann estimate of the centre of the differences. Report it with its confidence interval, and do not report the p-value alone.

walsh <- outer(d, d, "+") / 2
median(walsh[upper.tri(walsh, diag = TRUE)])
[1] 6.5

For the sunburn data, the Hodges–Lehmann estimate is that the burn with ointment A is higher by 6.5 points on the 20-point scale. The 96.1% confidence interval is -1 to 13, and \(p = 0.055\). The interval includes zero, so 9 people are too few to decide between the ointments.

5.7 Summary

  • The signed-rank test ranks the absolute paired differences, restores their signs, and adds the positive ranks.
  • The exact null distribution comes from the \(2^n\) sign patterns, because each sign is a fair coin under \(H_0\). No normal distribution is necessary.
  • One extreme value can make a t-test non-significant, but in the signed-rank test it can only take the largest rank.
  • A full report gives the Hodges–Lehmann estimate and its confidence interval with the p-value, and it states how R treated zeros and ties.