Week 6 · Assumptions and alternative tests

when you may use the bell, and what you do when you may not

Towards morning the whole wood was asleep.

Everyone had fallen asleep within 45 minutes, except the moth, with his phone in bed: he took 120 minutes.

“He’s spoiling my average,” said the bat, “I’m leaving him out.”

“Your average is an animal that doesn’t exist,” said the dormouse, “and he does exist.”

“And if I count him out,” the bat said at last, “he won’t have lain awake a minute less.”

He put them in a row, from early to late, with the moth at the back: not as 120 minutes but as the last one, however late that was.

What you learn this week

  • when you may use the bell of the z-test and the t-test
  • checking by eye whether your scores are skewed
  • transforming: pulling in a long tail with a log or a square root
  • working with ranks, also when two scores are equal
  • the Wilcoxon rank-sum test, for two independent groups
  • the Wilcoxon signed-rank test, for two paired measurements
  • the effect size r for both
  • what a permutation test does: understanding it, not running it yourself
  • in R: wilcox.test() and median()

When may you use the bell?

Remember? Statistics has no other goal than to predict and explain differences, in the population. This week you link differences in time to fall asleep to whether or not people have their phone in bed, and those times are skewed.

Since week 2 (Hypothesis tests for one mean) you haven’t been counting dots. You read your p-value off a smooth, symmetrical bell: the normal distribution for the z-test, the t-distribution for the t-test. That saves a lot of counting. But that bell is a promise, and a promise comes with conditions. Those conditions are called assumptions: things that have to hold, or the p-value is wrong.

Every test with a bell you have done so far asks for two.

  1. Independent observations. Everyone is in the sample once, and nobody influences anyone else’s score. Children from the same class, participants who talk to each other during the study: then this condition no longer holds. For a paired test it applies to the pairs: each pair stands apart from the other pairs.
  2. A sampling distribution that really is a bell. That is the case if the scores in the population are normally distributed. Or if your sample is big enough: then the means fall into a bell by themselves, even when the individual scores are skewed. That is the central limit theorem from week 2. In an exam this condition is called the assumption of normality.

How big is big enough? There is no fixed number for that. The more skewed the scores, the bigger the sample has to be before the means settle neatly into a bell.

With two independent groups there is traditionally one more: equal variances in both groups. The Welch version of the t-test, which R uses by default, doesn’t need it.

If the second condition doesn’t hold (the assumption is then violated), you’re stuck. The bell is then the wrong shape, and what the right shape is, you don’t know. No shape, no p-value.

TipRing the doorbell, or bang on the door

Checking assumptions is like dropping in on someone for a cup of tea. If the conditions are met, you ring the doorbell politely: you do the ordinary test.

If they aren’t, you have to get in another way. Then you bang on the door: you pick a different test, one for when the world is ugly.

What do you do when the world is ugly? Two ways out.

  • Transforming: converting the scores so they are less skewed, and then doing the ordinary test after all.
  • A test that doesn’t need a bell over your scores: a rank test (this week, the two by Wilcoxon) or a permutation test.

The tests with a bell are called parametric: they assume the population has a fixed shape that you describe with a few parameters, such as μx\mu_x and σx\sigma_x. A nonparametric test doesn’t need that shape.

Looking: is it skewed?

You check with your eyes whether your scores are normally distributed. Three things help:

  • a histogram: do you see a bell, or one long tail?
  • a boxplot: are there separate dots far away, outliers? In your head, turn it into a histogram: the tail is on the side of the separate dots.
  • the mean next to the median: in a symmetrical distribution they are at roughly the same place.

That last one is the quickest. A long tail pulls the mean towards it, away from where most people are. The median couldn’t care less: it simply points to the middle person, with half below and half above.

NoteThe example: time to fall asleep

A researcher asks 15 students how long it took them to fall asleep last night. Of them, eight were still on their phone in bed, and seven were not.

Two rows of dots on an axis from 0 to 120 minutes. Without a phone: 7 dots between 6 and 22, median and mean close together: 14 and 13.57. With a phone: 7 dots between 15 and 44, and one far to the right, at 120. There the median is at 29 and the mean further right, at 39.38.
Figure 1: Time to fall asleep for 15 students. Blue line: the median. Orange diamond: the mean. One student with a phone lay awake for 120 minutes.

How to read it: without a phone, the diamond and the line lie close together: the mean is 13.57 minutes, the median 14. With a phone, the diamond lies far to the right of the line: the median is 29, but the mean is 39.38. That is because of one student who lay awake for 120 minutes: that student drags the mean along, but not the median.

Leave that student out, and the mean of the other seven is only 27.86.

With so few people, a histogram tells you little: a few bars, and whether that is a bell, you can’t see. Then just lay them out as dots on a line, as above.

Is this reason enough not to trust the t-test? Yes. Two small groups, and in one of them an outlier that drags the mean along. This is where you bang on the door.

Transforming: pulling in the tail

Scores that are skewed to the right (lots of small values, a few very large ones) can be converted. Two conversions are common: the logarithm and the square root. In R those are log() and sqrt(). Careful: log() in R is the natural logarithm. On a calculator that is usually called ln; the log button there is a different one. Both conversions squeeze large numbers more than small ones.

What a transformation does to large numbers
minutes square root log
15 3.87 2.708
30 5.48 3.401
60 7.75 4.094
120 10.95 4.787

Look at the log column. From 15 to 30 minutes is a doubling, and so is 60 to 120. On the log scale those are steps of exactly the same size, 0.693 each. That is how the long tail on the right gets folded in.

Two rules:

  • Choose the transformation before you test. Not trying three first and then reporting the nicest p-value. That is cheating, just like choosing the direction of your test after you saw the data.
  • Transform the number in your null hypothesis too. If you test H0H_0: μx\mu_x = 20 minutes for the time to fall asleep, then after a log transformation you test against log(20), and after a square root against √20.

Ranks: only the order counts

Say you hold three perfumes under someone’s nose and ask: how much does each one impress you, from 0 to 100? They say 20, 70 and 90. Should you take it seriously that there are exactly 50 points between the first and the second? Better not. What you do believe: the third made the biggest impression, the first the smallest.

That is the idea behind a rank test. You throw the distances away and keep only the order.

  1. Put all the scores, from all groups together, in a row from small to large.
  2. Give them numbers: 1, 2, 3, … Those are the ranks.
  3. If two or more scores are equal (a tie), they all get the mean of the places they take up together.

In the example there are two students with exactly 15 minutes, one with a phone and one without. Together they take places 5 and 6, so they both get 5+62=5.5\dfrac{5 + 6}{2} = 5.5.

And that student with 120 minutes? That student simply gets rank 15, the highest. Whether that student lay awake for two hours or twenty: rank 15. So one outlier no longer carries extra weight: a rank test is robust to outliers.

The Wilcoxon rank-sum test

The Wilcoxon rank-sum test is for two independent groups. Use it when the scores are not normally distributed and the groups are small, or when your scores are only an order (ordinal). It is the alternative to the t-test for two independent groups. You will also meet it as the Mann–Whitney test: the same idea, a different name.

The hypotheses. In words:

H0H_0: neither group has systematically higher scores than the other
HaH_\text{a}: one of the two groups has systematically higher scores

In symbols, with md for the median, you write H0H_0: md1 = md2 against HaH_\text{a}: md1 ≠ md2: the medians in the two populations are equal. You may write that down: if the two distributions have the same shape, it says the same as the words above.

The idea. If there is no difference in time to fall asleep between the two groups, the ranks are mixed together at random, and each group gets its fair share. The mean rank of everyone together is N+12\dfrac{N + 1}{2}: here 15+12=8\dfrac{15 + 1}{2} = 8. If the seven students without a phone get their fair share, their ranks add up to about 7 × 8 = 56. If they come out far below that, they are systematically lower.

Time to fall asleep in minutes, with each student’s rank in the two groups together
without a phone rank with a phone rank
6 1 15 5.5
9 2 19 8
11 3 24 10
14 4 27 11
15 5.5 31 12
18 7 35 13
22 9 44 14
120 15
sum 31.5 sum 88.5

Step 1: the rank sum. Add up the ranks of one group. That is W. Take the group without a phone:

W=1+2+3+4+5.5+7+9=31.5 W = 1 + 2 + 3 + 4 + 5.5 + 7 + 9 = 31.5

TipAlways check

Add up the other group too: 88.5. All the ranks together must come to N(N+1)2\dfrac{N(N+1)}{2}, here 15×162=120\dfrac{15 \times 16}{2} = 120. And 31.5 + 88.5 = 120. If it doesn’t add up, there is a mistake in your ranks, and right now it is still easy to find.

Step 2: what do you expect if H0H_0 is true? The fair share from above, as a formula: the expected value of W. n1 is the group you added up:

μW=n1(n1+n2+1)2=7×(7+8+1)2=56 \mu_W = \dfrac{n_1 (n_1 + n_2 + 1)}{2} = \dfrac{7 \times (7 + 8 + 1)}{2} = 56

Step 3: how much does W wobble by chance? That is the standard deviation of W. You don’t need to know where this formula comes from: filling it in is enough.

σW=n1n2(n1+n2+1)12=7×8×1612=8.64 \sigma_W = \sqrt{\dfrac{n_1 \, n_2 \, (n_1 + n_2 + 1)}{12}} = \sqrt{\dfrac{7 \times 8 \times 16}{12}} = 8.64

You can see below what σW\sigma_W means. If H0H_0 is true, it makes no difference who gets which rank. Then every way of sharing out the 15 ranks between the two groups is equally possible: there are 6,435 of them. For each way, here is the rank sum of the group without a phone.

A bar chart in the shape of a bell, from 28 to 84, with its peak around 56. A blue bell curve lies almost exactly on top of it. Two orange dashed lines stand in the tails, at 31.5 and at 80.5; what lies on or beyond those lines is orange, and so low you can hardly see it. Together those orange bars hold 16 of the 6,435 ways, 8 in each tail.
Figure 2: All 6,435 ways to share out the 15 ranks between the two groups, each with the rank sum of the group without a phone. The blue line is the bell with μW\mu_W = 56 and σW\sigma_W = 8.64. Dashed: the real W = 31.5, and just as far out on the other side, 80.5. Orange: the ways at least as far from the middle as the real W.

How to read it: a bar counts how many of the 6,435 ways end up there. The tallest bar, at 56, counts 290. The bar your dashed line at 31.5 runs through counts only 3: so low you can hardly see it. So the group without a phone almost never gets a rank sum that low, if it makes no difference who gets which rank.

The middle of the hill is μW\mu_W = 56. The width is σW\sigma_W = 8.64. And your 31.5 lies far to the left, in the tail.

Step 4: the test statistic. How many times σW\sigma_W is your W away from the middle? That is a z-value, just as in week 2:

z=W−μWσW=31.5−568.64=−2.84 z = \dfrac{W - \mu_W}{\sigma_W} = \dfrac{31.5 - 56}{8.64} = −2.84

Step 5: the p-value. Hang on: wasn’t this supposed to be the test without a bell? Not on the minutes, no. Those are skewed. But W is a sum of ranks, and ranks are always just 1 to 15, however skewed the minutes were. So their sum settles neatly into a hill, and that hill lies almost exactly under the bell. On W the bell is allowed: one tail times two.

p=2×P(Z≤−2.84)=.005 p = 2 \times P(Z \leq −2.84) = .005

Without R, you look that probability up in Table A. A negative z is on the first page: row −2.8, column .04. There it says .0023, the small tail on the left. Times two: .0046, which to three decimals is the same .005. Have you come across a separate table for W in another book? You don’t need it here: with z, Table A is enough.

You can also see it from the boundary: |−2.84| is bigger than 1.96, so p < .05.

Step 6: the conclusion. .005 ≤ .05: you reject the null hypothesis that students with and without a phone in bed fall asleep equally fast. Students who are still on their phone in bed fall asleep systematically later.

NoteHow big is the difference? The effect size r

r=|z|N r = \dfrac{|z|}{\sqrt{N}}

with N the number of scores. With two separate groups everyone has one score, so N is simply everyone in both groups together. Here r=2.8415=.73r = \dfrac{2.84}{\sqrt{15}} = .73.

Cohen’s rule of thumb: around .1 is a small effect, around .3 a medium one and around .5 a large one. So the difference in time to fall asleep between students with and without a phone is a large effect.

TipWhich group do you add up?

It doesn’t matter. Add up the group with a phone, and W = 88.5, μW=64\mu_W = 64 and z = 2.84. Same number, other sign: the same p, the same conclusion. Just make sure that n1 in the formula for μW\mu_W is the group you added up.

And the t-test? On the same data it finds p = .069: with the t-test, the difference in time to fall asleep between the two groups is not significant. That one student with 120 minutes makes the spread in the phone group so large that the t-test becomes unsure. In the rank-sum test, that student is simply number 15.

Does this mean you always pick the test that is significant? No. The choice was made above, when you looked at the dots, before there was a p-value. If you look at both p-values first and then choose, you’re cheating.

By hand you work out the simple version: ranks, W, z. In R you can do exactly that:

# times to fall asleep, in minutes
no_phone <- c(6, 9, 11, 14, 15, 18, 22)
phone    <- c(15, 19, 24, 27, 31, 35, 44, 120)

# ranks of everyone together; "average" (the default) averages a tie
ranks <- rank(c(no_phone, phone), ties.method = "average")

# W: the rank sum of the first 7 (without a phone)
W <- sum(ranks[1:7])
W
[1] 31.5
mu    <- 7 * (7 + 8 + 1) / 2
sigma <- sqrt(7 * 8 * (7 + 8 + 1) / 12)
z <- (W - mu) / sigma
z
[1] -2.835324
# two-tailed: one tail times two
2 * pnorm(-abs(z))
[1] 0.004577922

And with the function that does it all in one go:

wilcox.test(no_phone, phone, alternative = "two.sided", mu = 0, paired = FALSE,
            exact = NULL, correct = TRUE)

    Wilcoxon rank sum exact test

data:  no_phone and phone
W = 3.5, p-value = 0.002486
alternative hypothesis: true location shift is not equal to 0

The arguments after no_phone, phone are the defaults; leave them out and R picks these. So the short form is wilcox.test(no_phone, phone), with exactly the same output. One of them is not a yes or no: exact = NULL means R chooses for itself. If both groups have fewer than 50 scores, it calculates exactly, and since R 4.6 also when there are equal scores in them, like the two times 15 here. correct = TRUE only does something when R uses the bell.

Two things are different.

  • R’s W is not your W. R subtracts the smallest possible rank sum from it. The seven lowest ranks together, 1 to 7, make 28; and 31.5 − 28 = 3.5. Both are right, just with a different zero point.
  • R’s p is slightly different (.002 against your .005). R doesn’t use the bell but the hill itself from Figure 2: it counts the orange bars. That is the word exact in the heading of the output. The same decision.

In R you just use the default. If you still want to see your hand-worked number: with exact = FALSE, correct = FALSE R gives .005 as well, just like you.

If you are given R output and have to work out z yourself, first add that smallest possible rank sum back on: 3.5 + 28 = 31.5. Only then does it fit the formulas above.

The Wilcoxon signed-rank test

For two paired measurements: the same people before and after, or twice under different conditions. It is the alternative to the paired t-test. Use it when the difference scores are not normally distributed and there are only a few people, or when your scores are only an order.

The name says what you do. The sign is the plus or minus of a difference: is the difference positive or negative? You first give the differences a rank without their sign, and then put the sign of each difference back on its rank: a signed rank.

The idea: pluses and minuses. You look at the difference scores. If nothing is going on, there are about as many pluses as minuses, and they are about the same size. If you see mostly pluses, and the big differences are pluses as well, then something is going on.

H0H_0: in the population, the difference scores lie above zero as often as below
HaH_\text{a}: the difference scores lie systematically above or below zero

In symbols you write H0H_0: md1 = md2 here too, just as for the rank-sum test.

NoteThe example: worry time

Nine poor sleepers try two weeks of worry time: a fixed quarter of an hour every afternoon for worrying, so that it needs to happen less at night. Their worry score is measured before and after. With nine people you can’t see whether the difference scores are normally distributed. So you don’t know, and then you pick the test that doesn’t need to know: the signed-rank test.

Step 1: T+T^+. That takes five moves:

  1. Work out the difference for each person: before − after. A positive difference here is a drop in worrying.
  2. If a difference is exactly zero, you throw that person out. n is the number of people left. Here nobody is zero, so n = 9.
  3. Rank the differences ignoring the sign: the smallest difference gets 1. A tie again gets the mean.
  4. Put the sign of the difference on the rank.
  5. Add up the ranks with a plus. That is T+T^+.
Worry score before and after two weeks of worry time; difference = before − after
person before after difference rank signed rank
1 61 55 6 5 +5
2 58 55 3 2.5 +2.5
3 52 55 −3 2.5 −2.5
4 66 65 1 1 +1
5 70 62 8 6 +6
6 57 45 12 8 +8
7 63 58 5 4 +4
8 68 59 9 7 +7
9 55 40 15 9 +9

There is one tie in it: a difference of +3 and one of −3. Without the sign they are both 3, in places 2 and 3, so they both get 2.5. Only after that does the sign come back.

Add up the ranks with a plus:

T+=5+2.5+1+6+8+4+7+9=42.5 T^+ = 5 + 2.5 + 1 + 6 + 8 + 4 + 7 + 9 = 42.5

TipAlways check

Work out T−T^- as well, the ranks with a minus: 2.5. Together they must be all the ranks, n(n+1)2=9×102=45\dfrac{n(n+1)}{2} = \dfrac{9 \times 10}{2} = 45. And 42.5 + 2.5 = 45.

Step 2: what do you expect if H0H_0 is true? As much plus as minus: T+T^+ is then half of all the ranks. Half of n(n+1)2\dfrac{n(n+1)}{2} is:

μT+=n(n+1)4=9×104=22.5 \mu_{T^+} = \dfrac{n(n+1)}{4} = \dfrac{9 \times 10}{4} = 22.5

Step 3: how much does T+T^+ wobble by chance? Here too: filling it in is enough.

σT+=n(n+1)(2n+1)24=9×10×1924=8.44 \sigma_{T^+} = \sqrt{\dfrac{n(n+1)(2n+1)}{24}} = \sqrt{\dfrac{9 \times 10 \times 19}{24}} = 8.44

Step 4: the test statistic.

z=T+−μT+σT+=42.5−22.58.44=2.37 z = \dfrac{T^+ - \mu_{T^+}}{\sigma_{T^+}} = \dfrac{42.5 - 22.5}{8.44} = 2.37

Step 5: the p-value. The bell again, one tail times two:

p=2×P(Z≥2.37)=.018 p = 2 \times P(Z \geq 2.37) = .018

In Table A there is one more step this time. The table always gives the probability to the left of z: at 2.37, row 2.3 and column .07, that is .9911. You want the small tail on the right, so 1 − .9911 = .0089. Times two: .0178, which to three decimals is the same .018. (You can also look up −2.37 instead, on the first page: the bell is symmetrical, so there you find the same .0089 straight away.)

Step 6: the conclusion. .018 ≤ .05: you reject the null hypothesis that the worry score stays the same after two weeks of worry time. After the worry time, the worry score is systematically lower than before. Whether that is because of the worry time, this test doesn’t say: there is no group that didn’t do it.

NoteThe effect size r for the signed-rank test

r=|z|2n r = \dfrac{|z|}{\sqrt{2n}}

The same rule as for the rank-sum test: you divide by the square root of the number of scores. Only here everyone has two, before and after. So the number of scores is twice the number of people: 2n. Here r=2.372×9=.56r = \dfrac{2.37}{\sqrt{2 \times 9}} = .56: the difference in worry score between before and after is a large effect.

TipBefore − after, or after − before?

Both are fine. Turn it round, and the pluses become minuses: T+T^+ and T−T^- swap places, and z gets a minus. The same p, the same conclusion. In an exercise, do check which order is given, because the number T+T^+ depends on it.

# the worry scores, before and after
before <- c(61, 58, 52, 66, 70, 57, 63, 68, 55)
after  <- c(55, 55, 55, 65, 62, 45, 58, 59, 40)

d <- before - after
# does anyone have a difference of 0? then take them out first: d <- d[d != 0]
ranks <- rank(abs(d))

# T+: the ranks of the positive differences
Tplus <- sum(ranks[d > 0])
Tplus
[1] 42.5
n <- length(d)
z <- (Tplus - n * (n + 1) / 4) / sqrt(n * (n + 1) * (2 * n + 1) / 24)
2 * pnorm(-abs(z))
[1] 0.01781719
# and the test itself; here R calls T+ V
wilcox.test(before, after, paired = TRUE, exact = NULL, correct = TRUE)

    Wilcoxon signed rank exact test

data:  before and after
V = 42.5, p-value = 0.01562
alternative hypothesis: true location shift is not equal to 0

Here R calls T+T^+ V: 42.5, exactly what you found by hand. The p-value (.016) is the exact one again, not the one from the bell; the decision is the same.

If someone has a difference of zero, V can differ from your T+T^+. How that works is explained further down, under In R.

The same six steps, twice. Put the two tests side by side, and you see that it is one recipe with different ingredients:

The rank-sum test and the signed-rank test, step by step
step rank-sum test signed-rank test
1 W: the rank sum of one group T+T^+: the rank sum of the pluses
2 μW=n1(n1+n2+1)2\mu_W = \dfrac{n_1(n_1+n_2+1)}{2} μT+=n(n+1)4\mu_{T^+} = \dfrac{n(n+1)}{4}
3 σW=n1n2(n1+n2+1)12\sigma_W = \sqrt{\dfrac{n_1 n_2 (n_1+n_2+1)}{12}} σT+=n(n+1)(2n+1)24\sigma_{T^+} = \sqrt{\dfrac{n(n+1)(2n+1)}{24}}
4 z=W−μWσWz = \dfrac{W - \mu_W}{\sigma_W} z=T+−μT+σT+z = \dfrac{T^+ - \mu_{T^+}}{\sigma_{T^+}}
5 p: one tail times two p: one tail times two
6 conclusion conclusion
effect size r=|z|Nr = \dfrac{\lvert z \rvert}{\sqrt{N}}, N = everyone r=|z|2nr = \dfrac{\lvert z \rvert}{\sqrt{2n}}, n = pairs

The permutation test: week 1 again

Remember the dots from week 1? You pretended H0H_0 was true, made a hundred imaginary samples, and counted how many dots lay at least as far from the middle as your result. That was the p-value.

A permutation test does exactly the same. Only it doesn’t make the dots in an imaginary population, but out of your own data. No bell, no normal distribution.

NoteThe example: training or not

Eight students drew a card: four got sleep training, four didn’t. That draw will matter in a moment. By how many points did their worry score drop?

  • training: 9, 6, 12 and 8; mean 8.75
  • control: 2, 5, −1 and 3; mean 2.25

The difference in mean drop is 6.5. Real, or chance?

Suppose H0H_0 is true: the training does nothing. Then each of these eight would have had exactly the same drop, whichever card they got. And because chance decided who got which card, any other way of handing out the cards was just as likely. Then the card, training or control, means nothing. So you may shuffle the cards. That is called permuting.

Shuffling. Leave the eight drops where they are, and hand out the four training cards again among the eight people. In how many ways can you do that? In 70. For each way, work out the difference in mean drop. Each way becomes one dot (a small square in the plot below).

A dot plot of 70 open squares on an axis from −6.5 to 6.5. The tallest stack stands above 0, with 8 squares; further from 0 the stacks get lower, roughly, with a few bumps. At the far left, at −6.5, and at the far right, at 6.5, there is one orange square.
Figure 3: All 70 ways to hand out the cards. Each square is the difference in mean drop (training minus control) in one shuffled world. Orange: at least as far from 0 as the real difference, 6.5.

How to read it: the tallest stack stands above 0: eight of the 70 ways give no difference at all. At the far right, at the real difference of 6.5, there is only one square: the shuffling gives a difference that large only once in 70.

This is a sampling distribution again: this is what the difference looks like when the card means nothing. A hill around 0, as it should be.

Counting. How many dots lie at least 6.5 from 0, on both sides? Two: the real one, and its mirror image (the four biggest drops all in the control group). There are only two here because the real difference is the biggest one possible. That is often not the case, so always count. So

p=270=.029 p = \dfrac{2}{70} = .029

and .029 ≤ .05: you reject the null hypothesis that the training has no effect on worrying. Exactly as in week 1: both sides count, and the boundary itself counts too.

With bigger groups you can no longer go through all the ways. With twelve against twelve there are already 2,704,156; with the 30 people of the practice dataset, 15 against 15, already 155,117,520. Then you let the computer shuffle at random, say ten thousand times, and count among those ten thousand dots. That is called a random permutation test. The p-value then becomes a very good approximation, and it differs a tiny bit each time.

In each shuffled world you can work out any number: the difference in means, as here, but also the difference in medians. That last one, like ranks, cares little about an outlier.

ImportantUnderstand it, don’t run it

You don’t need to be able to do a permutation test yourself. But you do need to understand three things:

  • what gets shuffled: the group names, not the scores;
  • what one dot is: the difference in one shuffled world, in which H0H_0 is true;
  • what you count: the dots that lie at least as far from 0 as the real difference, on both sides.

And the rank-sum test? Look again at the hill of rank sums in Figure 2. That was a permutation test: the group names shuffled, only over ranks instead of minutes. Count the orange bars there, and 16 of the 6,435 ways lie at least as far from 56 as the real 31.5: 166435=.002\dfrac{16}{6435} = .002. That is the very same exact p-value that wilcox.test() gave. The bell you use by hand is an approximation of that count.

With or without a bell over the scores

This week’s tests next to the earlier ones
you compare bell over the scores no bell over the scores
two independent groups t-test (Welch) Wilcoxon rank-sum test
two paired measurements paired t-test Wilcoxon signed-rank test
any difference you can calculate permutation test

How to pick the right test for a question in one go comes in week 7 (Choosing a test, and an overview).

In R: wilcox.test()

This week you do two things in R: look at whether the scores are skewed, and run the Wilcoxon tests. You use the practice dataset sleepstudy again: 30 poor sleepers, half of them with sleep training, with a worry score before and after.

load("sleepstudy.RData")

Two groups. Did worrying drop more in the training group than in the control group? First make a column with the drop, and look:

sleepstudy$worry_drop <- sleepstudy$worry_before - sleepstudy$worry_after

boxplot(worry_drop ~ group, data = sleepstudy, ylab = "drop")

# the median per group
tapply(sleepstudy$worry_drop, sleepstudy$group, median)
 control training 
       2        4 
Two boxplots side by side, control on the left and training on the right. The thick line in the middle, the median, is at 2 for control and at 4 for training. Below the control group there is one separate circle, at -11.
Figure 4: Drop in worry score (before minus after), per group.

How to read it: the thick line in a box is the median. For training it lies higher than for control, at 4 against 2: half of the training group dropped by at least 4 points, half of the control group by at least 2. But the boxes overlap, from 1.5 to 4: whether that difference is more than chance, the test below tells you.

Then the rank-sum test. You read the ~ as ‘split by’: the drop, split by group.

wilcox.test(worry_drop ~ group, data = sleepstudy)

    Wilcoxon rank sum exact test

data:  worry_drop by group
W = 80, p-value = 0.1813
alternative hypothesis: true location shift is not equal to 0

p = .18, so you don’t reject the null hypothesis: with these 30 people there is no systematic difference in drop between the two groups to be seen. (The t-test on the same question gives p = .11, and doesn’t reject either.)

Which group does R add up? With ~, the group that comes first in the alphabet: control. (If you give R two lists of numbers, as in the check of the rank-sum test, it adds up the first list.) Their rank sum is 200; R subtracts the smallest possible one, 15×162=120\dfrac{15 \times 16}{2} = 120, and reports W = 80.

Two paired measurements. Did worrying drop within the training group of the sleep study? Select the rows, and give R the two columns with paired = TRUE:

training <- sleepstudy[sleepstudy$group == "training", ]

wilcox.test(training$worry_before, training$worry_after, paired = TRUE,
            exact = NULL, correct = TRUE)

    Wilcoxon signed rank exact test

data:  training$worry_before and training$worry_after
V = 113.5, p-value = 0.0007324
alternative hypothesis: true location shift is not equal to 0

p < .001: you reject the null hypothesis that worrying stayed the same in the training group. It dropped systematically.

Here R calls T+T^+ V. But careful: in the training group there are two people with no difference, and then V is not the number you would find by hand. For your conclusion it makes no difference here. By hand the rule stays: a difference of zero goes out.

A difference of zero. By hand you throw out the two people with no difference, and then you find T+T^+ = 89.5. R (from version 4.6) lets them take part in the ranking in its exact test, and so arrives at V = 113.5. Set exact = FALSE, and R leaves the zeros out, just like you, and reports V = 89.5, with p = .002. Both calculations reject the null hypothesis that worrying stayed the same in the training group.

An older R. Do you get a warning like cannot compute exact p-value with ties, and does the heading say with continuity correction? Then you have an R from before version 4.6. That one could not calculate exactly with ties and switched to the bell instead, with a small correction. An older R also always leaves out a difference of zero; V and the p-value are then different from above. The decision here is the same. You can see which version you have with R.version.string.

Practice

You work out a p-value in R, with 2 * pnorm(-abs(z)). Or you reason it out with the boundary 1.96: if |z| is above it, p < .05; if it is below, p > .05. For a decision that is enough. If you want to see the p itself, look up the small tail in Table A and multiply it by two.

NoteExercise 6.1 — Concepts
  1. What is a nonparametric test?
  2. Name two situations in which a Wilcoxon test fits better than a t-test.
  3. Which Wilcoxon test is for paired measurements, and which for two independent groups?
  4. What do you do in the rank-sum test when two scores are equal?
  5. Write down the formulas for the expected value and the standard deviation of W in the rank-sum test.
  6. And those for T+T^+ in the signed-rank test.
  1. A test that doesn’t assume the population has a fixed shape, such as the normal distribution. Rank tests and permutation tests are nonparametric.

  2. When the scores are not normally distributed and the groups are small (then the central limit theorem doesn’t help enough), and when the scores are only an order (ordinal).

  3. Paired: the signed-rank test. Two independent groups: the rank-sum test.

  4. They both get the mean of the ranks they share. In places 4 and 5, that becomes 4.5 and 4.5.

  5. μW=n1(n1+n2+1)2\mu_W = \dfrac{n_1(n_1 + n_2 + 1)}{2} and σW=n1n2(n1+n2+1)12\sigma_W = \sqrt{\dfrac{n_1 n_2 (n_1 + n_2 + 1)}{12}}, with n1 the group whose ranks you added up.

  6. μT+=n(n+1)4\mu_{T^+} = \dfrac{n(n+1)}{4} and σT+=n(n+1)(2n+1)24\sigma_{T^+} = \sqrt{\dfrac{n(n+1)(2n+1)}{24}}, with n the number of pairs without a difference of zero.

NoteExercise 6.2 — The rank-sum test by hand

Do students who still drink coffee in the evening sleep more restlessly? A researcher asks 17 students how often they woke up in the night over the past week. Of them, eight still drank coffee after six in the evening, and nine didn’t.

Number of times woken up in a week
times woken up
coffee 5, 9, 3, 12, 6, 4, 2, 11
no coffee 2, 4, 7, 6, 1, 5, 3, 0, 4

Counts like these are often skewed, and the groups are small. You do the rank-sum test by hand, with the normal distribution as an approximation.

  1. Give all the scores their rank.
  2. Add up the ranks of the coffee group: W.
  3. Calculate μW\mu_W.
  4. Calculate σW\sigma_W.
  5. Calculate z.
  6. What is the p-value (two-tailed)? With R, or with the boundary 1.96.
  7. What is your conclusion (α = .05)?
  8. Calculate the effect size r. How big is the difference in the number of times woken up?
  1. See the full worked answer.
  2. W = 88.
  3. μW\mu_W = 72.
  4. σW\sigma_W = 10.39.
  5. z = 1.54.
  6. p = .12.
  7. Don’t reject.
  8. r = .37: the difference in the number of times woken up is a medium effect.
  1. All 17 scores in a row, with their place and their rank. There are lots of ties: the two 2s are in places 3 and 4, so both get 3.5; the three 4s are in places 7, 8 and 9, so all three get 8.

    Places 1 to 9, in order of score
    place 1 2 3 4 5 6 7 8 9
    score 0 1 2 2 3 3 4 4 4
    coffee? no no yes no yes no yes no no
    rank 1 2 3.5 3.5 5.5 5.5 8 8 8
    Places 10 to 17
    place 10 11 12 13 14 15 16 17
    score 5 5 6 6 7 9 11 12
    coffee? yes no yes no no yes yes yes
    rank 10.5 10.5 12.5 12.5 14 15 16 17

    Per group, with the rank in brackets:

    • coffee: 5 (10.5), 9 (15), 3 (5.5), 12 (17), 6 (12.5), 4 (8), 2 (3.5), 11 (16)
    • no coffee: 2 (3.5), 4 (8), 7 (14), 6 (12.5), 1 (2), 5 (10.5), 3 (5.5), 0 (1), 4 (8)
  2. W=10.5+15+5.5+17+12.5+8+3.5+16=88W = 10.5 + 15 + 5.5 + 17 + 12.5 + 8 + 3.5 + 16 = 88.

    Check: the no-coffee group adds up to 65, and 88 + 65 = 153 = 17×182\dfrac{17 \times 18}{2}.

  3. μW=8×(8+9+1)2=72\mu_W = \dfrac{8 \times (8 + 9 + 1)}{2} = 72.

  4. σW=8×9×1812=10.39\sigma_W = \sqrt{\dfrac{8 \times 9 \times 18}{12}} = 10.39.

  5. z=88−7210.39=1.54z = \dfrac{88 - 72}{10.39} = 1.54.

  6. p=2×P(Z≥1.54)=.12p = 2 \times P(Z \geq 1.54) = .12. In R: 2 * pnorm(-abs(z)). Or with the boundary: 1.54 is below 1.96, so p > .05.

  7. .12 > .05: you don’t reject the null hypothesis that students with and without evening coffee wake up equally often. That doesn’t mean there is no difference in how often students with and without evening coffee wake up. With 17 students, the difference isn’t strong enough to see.

  8. r=1.5417=.37r = \dfrac{1.54}{\sqrt{17}} = .37: the difference in the number of times woken up between the two groups is a medium effect. Not significant, and yet not nothing: with more students, this difference might have been significant.

Had you added up the no-coffee group: W = 65, μW\mu_W = 81, z = −1.54. The same p.

NoteExercise 6.3 — Exercise 6.2 in R
  1. Put the scores from exercise 6.2 into R, as two lists of numbers called coffee and no_coffee, and do the rank-sum test with wilcox.test().
  2. R reports a different W from the one you found by hand. How are they related?
  3. Do you get the same p-value as in 6.2? The same decision?
coffee <- c(5, 9, 3, 12, 6, 4, 2, 11)
no_coffee   <- c(2, 4, 7, 6, 1, 5, 3, 0, 4)

wilcox.test(coffee, no_coffee, exact = NULL, correct = TRUE)

    Wilcoxon rank sum exact test

data:  coffee and no_coffee
W = 52, p-value = 0.1334
alternative hypothesis: true location shift is not equal to 0
  1. R subtracts the smallest possible rank sum of the coffee group: the eight lowest ranks together, 8×92=36\dfrac{8 \times 9}{2} = 36. And 88 − 36 = 52.

  2. Almost: R gives .13, you .12. R calculates with the real distribution of W (the word exact), you with the bell. The same decision: don’t reject.

NoteExercise 6.4 — The signed-rank test by hand

Do you get slower after a short night? Eight students do a reaction-time task twice: once after a normal night, once after a night of four hours. Reaction times are often skewed.

Reaction time in milliseconds
student 1 2 3 4 5 6 7 8
normal night 410 380 450 500 360 440 390 470
short night 470 370 520 610 400 450 480 520
  1. Which test fits here, and why?
  2. Calculate T+T^+, with difference = short night − normal night.
  3. Calculate μT+\mu_{T^+} and σT+\sigma_{T^+}.
  4. Calculate z, and look up the p-value (two-tailed) in Table A. Then check it with 2 * pnorm(-abs(z)). In the exam you don’t have to look anything up; you do it here to check yourself.
  5. Calculate the effect size r.
  6. What is your conclusion (α = .05)?
  1. The signed-rank test: two paired measurements, few people, skewed scores.
  2. T+T^+ = 34.5.
  3. μT+\mu_{T^+} = 18; σT+\sigma_{T^+} = 7.14.
  4. z = 2.31; in Table A p = 2 × .0104 = .0208, with pnorm() .0209: both give p = .021.
  5. r = .58.
  6. Reject.
  1. The same eight students were measured twice: paired. With eight people you can’t see whether the difference scores are normally distributed, and reaction times are often skewed. So the signed-rank test, not the paired t-test.

  2. The differences, their rank without the sign, and the sign put back:

    Reaction time in milliseconds; difference = short night − normal night
    student normal night short night difference rank signed rank
    1 410 470 60 5 +5
    2 380 370 −10 1.5 −1.5
    3 450 520 70 6 +6
    4 500 610 110 8 +8
    5 360 400 40 3 +3
    6 440 450 10 1.5 +1.5
    7 390 480 90 7 +7
    8 470 520 50 4 +4

    There is a tie: −10 and +10 are both 10 without the sign, in places 1 and 2, so both get 1.5. Nobody has a difference of zero, so n = 8.

    T+=5+6+8+3+1.5+7+4=34.5T^+ = 5 + 6 + 8 + 3 + 1.5 + 7 + 4 = 34.5. Check: T−T^- = 1.5, and together 36 = 8×92\dfrac{8 \times 9}{2}.

  3. μT+=8×94=18\mu_{T^+} = \dfrac{8 \times 9}{4} = 18 and σT+=8×9×1724=7.14\sigma_{T^+} = \sqrt{\dfrac{8 \times 9 \times 17}{24}} = 7.14.

  4. z=34.5−187.14=2.31z = \dfrac{34.5 - 18}{7.14} = 2.31, and p=2×P(Z≥2.31)p = 2 \times P(Z \geq 2.31).

    In Table A, in the part for positive z, row 2.3 and column .01, you find .9896: the probability on the left. The small tail is on the right, so 1 − .9896 = .0104, and two-tailed 2 × .0104 = .0208. With 2 * pnorm(-abs(z)) you get .0209. The difference in the fourth decimal comes from the table rounding its probabilities to four decimals: R gives pnorm(2.31) = .98956, and the table prints that as .9896. Times two, that small difference becomes twice as big. To three decimals both are .021.

  5. r=2.312×8=.58r =\dfrac{2.31}{\sqrt{2 \times 8}} = .58: the difference in reaction time between a short and a normal night is a large effect. If you divide by 8\sqrt{8} by mistake, you end up with .82.

  6. .021 ≤ .05: you reject the null hypothesis that the reaction time after a short night is the same as after a normal night. After a short night, students react systematically more slowly.

In R: wilcox.test(short, normal, paired = TRUE, exact = NULL, correct = TRUE) gives V = 34.5 (your T+T^+) and the exact p = .023.

So you have three numbers for the same p:

  • .0208 from Table A,
  • .0209 from pnorm(),
  • .023 from wilcox.test().

All three are below .05: the same decision. The first two lay the bell over T+T^+. With few people, R counts through every possible order; that is the word exact, and you saw in exercise 6.3c why that gives a different number. In a report, you give the p from R.

Put the lists the other way round, wilcox.test(normal, short, paired = TRUE), and R reports V = 1.5: then it calculates normal − short night.

NoteExercise 6.5 — Look, then choose

Use sleepstudy, with the column worry_drop from In R above.

  1. Make a histogram of the drop for each group. Use hist(sleepstudy$worry_drop[sleepstudy$group == "training"]), and the same for the control group.
  2. For each group, compare the mean with the median.
  3. Do you find the t-test acceptable here? Why or why not?
  4. Do the t-test and the rank-sum test. Which p-values do you get?
  5. Someone says: “I’ll just report the smaller of the two.” What do you make of that?
hist(sleepstudy$worry_drop[sleepstudy$group == "training"])
hist(sleepstudy$worry_drop[sleepstudy$group == "control"])
tapply(sleepstudy$worry_drop, sleepstudy$group, mean)
 control training 
1.066667 3.466667 
tapply(sleepstudy$worry_drop, sleepstudy$group, median)
 control training 
       2        4 
  1. With 15 people per group, a histogram is rough: a few bars. No long tail. In the control group one person does stand out, with a drop of −11: for that person worrying actually went up a lot. The boxplot in In R draws that person as a separate circle.

  2. Mean and median are not far apart in either group: control 1.07 against 2, training 3.47 against 4.

  3. There is something to be said for it, and something against. No long tail, and mean and median are close together: the t-test can be defended. But 15 per group is not a lot, and that one outlier pulls at the mean of the control group. There is no wrong answer here, as long as you explain your choice, and as long as you make it before you test.

  4. Both tests, and only their p-value:

    t.test(worry_drop ~ group, data = sleepstudy, var.equal = FALSE)$p.value
    [1] 0.1108642
    wilcox.test(worry_drop ~ group, data = sleepstudy)$p.value
    [1] 0.1813086

    t-test: .11. Rank-sum test: .18. With neither of them is the difference in drop between the groups significant.

  5. That is cheating. If you choose the test by its outcome, the chance of a false alarm becomes bigger than the α you agreed on. You choose the test on what you saw in a to c, before you have a p-value.

NoteExercise 6.6 — Shuffling, three against three

Six students: three sleep with earplugs, three without. How often did they wake up over the past week?

  • with earplugs: 1, 5 and 3
  • without: 4, 8 and 9
  1. What is the difference in the mean number of times woken up (with minus without)?
  2. You do a permutation test. What do you shuffle, and in how many ways can you do it?

Below are all the ways as dots. Nothing is coloured here: count for yourself.

A dot plot of 20 open squares on an axis from −4.67 to 4.67. Stacks of two squares at −2, −1.33, −0.67, 0, 0.67, 1.33 and 2; a single square at −4.67, −4, −3.33, 3.33, 4 and 4.67.
Figure 5: All 20 ways to give three of the six students the card with earplugs. Each square is the difference in the mean number of times woken (with minus without).

How to read it: each square is one way of handing out the cards. From −2 to 2 there are always two stacked on top of each other; further out, after a gap, a single one each time: the shuffling gives a small difference more often than a large one.

  1. What is the p-value (two-tailed)?
  2. What is the smallest possible p-value with three against three? What does that mean for such a small study?
  3. How would you do this with the 30 people of sleepstudy?
  1. 3 − 7 = −4.

  2. The cards with and without, over the same six scores. Choose three of the six for with: you can do that in 20 ways.

  3. Count the dots that lie at least 4 from 0, on both sides: 4. So p=420=.20p = \dfrac{4}{20} = .20. Don’t reject.

  4. The smallest possible is that only the real way of handing out the cards and its mirror image lie that far out: 220=.10\dfrac{2}{20} = .10. That is always more than .05. So with three against three, two-tailed, you simply cannot reject, however big the difference is. A study like that is too small to be able to find anything.

  5. With 15 against 15 there are 155,117,520 ways: too many to go through. Then you let the computer shuffle at random, say ten thousand times: a random permutation test.

Exam block

This is how you might meet it in the exam: as a multiple-choice question with four options. The exam has 30 of them. Below there are also a few questions you fill in yourself or answer with yes or no; the exam does not have those, they are extra practice. All you need is your calculator and your cheat sheet: where you need a p-value, it is given in the question, or you decide with the boundary 1.96. The exam does not ask you to look anything up in Table A; you did that in exercise 6.4, to check yourself.

NoteQuestion 1 — multiple choice

Twelve people are given a medicine and measured before and after. The difference scores are very skewed. Which test fits best?

  1. the t-test for two independent groups
  2. the Wilcoxon rank-sum test
  3. the Wilcoxon signed-rank test
  4. the χ²-test

C. Before and after in the same people is paired, and skewed difference scores in twelve people call for a test that doesn’t need a bell over the scores. B is for two separate groups.

NoteQuestion 2 — multiple choice

Eight people are measured before and after. These are the scores:

Scores before and after
person 1 2 3 4 5 6 7 8
before 12 15 9 14 11 16 10 13
after 9 15 7 10 12 11 6 11

What is the expected value of T+T^+ if H0H_0 is true?

  1. 14
  2. 18
  3. 28
  4. 36

A. Person 2 has the same score before and after: a difference of zero, and that goes out. So n = 7, and μT+=7×84=14\mu_{T^+} = \dfrac{7 \times 8}{4} = 14.

B is the trap: then you counted the zero in (8×94\dfrac{8 \times 9}{4}). C is the sum of all the ranks, n(n+1)2\dfrac{n(n+1)}{2}, and D is that sum with the zero included.

NoteQuestion 3 — fill in

Same data as question 2, with difference = before − after. What is T+T^+?

27. The differences are 3, 0, 2, 4, −1, 5, 4 and 2. Without the zero, 7 are left. In order without the sign, with their rank:

The differences without the zero, from small to large (ignoring the sign)
difference −1 2 2 3 4 4 5
rank 1 2.5 2.5 4 5.5 5.5 7

Only the −1 has a minus, with rank 1. All 7 ranks together make 28, so T+T^+ = 28 − 1 = 27.

NoteQuestion 4 — multiple choice

Group A scores 3, 7, 8 and 12; group B scores 5, 8, 10, 14 and 15. What is the rank sum W of group A?

  1. 15
  2. 15.5
  3. 16
  4. 29.5

B. The two 8s (one in each group) are in places 4 and 5 and both get 4.5. Group A: 1 + 3 + 4.5 + 7 = 15.5. You get A and C if you don’t average the tie; D is the rank sum of group B.

NoteQuestion 5 — multiple choice

What happens in a permutation test?

  1. You keep drawing a new sample from the population.
  2. You shuffle the group names over the same scores, and work out the difference each time.
  3. You replace the scores with ranks and add them up per group.
  4. You lay a normal distribution over the scores.

B. The scores stay where they are; only who belongs to which group gets shuffled. A is the imaginary sampling distribution of week 1, C is what you do by hand in the rank-sum test, and D is exactly what a permutation test does not need.

NoteQuestion 6 — multiple choice

A researcher shuffles the group names 1,000 times. In 11 of those, the difference is at least as big as the real difference, and in 7 it is at least as big the other way. What is the two-tailed p-value?

  1. .011
  2. .018
  3. .036
  4. .009

B. Both sides count: 11+71000=.018\dfrac{11 + 7}{1000} = .018. A is only one side. C doubles what was already two sides, and D halves it.

NoteQuestion 7 — yes or no

A researcher does the t-test and the rank-sum test on the same data. The t-test gives p = .068, the rank-sum test p = .041. They report the rank-sum test, because it is significant. Is that allowed?

No. You choose the test beforehand, on what you know about the data: skewed or not, big or small, paired or not. Whoever chooses by the p-value makes the chance of a false alarm bigger than α.

NoteQuestion 8 — multiple choice

A signed-rank test on 12 people gives z = 1.83. How big is the difference between the two measurements, expressed as r?

  1. r = .37, a medium effect
  2. r = .53, a large effect
  3. r = .15, a small effect
  4. you can’t say without the p-value

A. r=|z|2n=1.8324=.37r = \dfrac{|z|}{\sqrt{2n}} = \dfrac{1.83}{\sqrt{24}} = .37. B divides by the square root of 12 instead of 24: in the signed-rank test you count the scores, not the people. C simply divides by the number of people, without the square root and without the 2.

NoteQuestion 9 — yes or no

You test H0H_0: μx\mu_x = 30 for the number of minutes students spend on sport per day. The scores are skewed, so you first take everyone’s logarithm. Do you then still test against 30?

No. You convert the number in your null hypothesis in the same way: you test against log(30) = 3.40.

NoteQuestion 10 — multiple choice

In a rank-sum test with 9 and 11 people, you find W = 71 for the first group by hand. On the same data R reports W = 26. What is going on?

  1. You made a calculation error.
  2. R adds up the other group.
  3. R subtracts the smallest possible rank sum from your W.
  4. R has applied a correction for ties.

C. The smallest possible rank sum of 9 people is 9×102=45\dfrac{9 \times 10}{2} = 45, and 71 − 45 = 26. Your W and R’s are both right, with a different zero point.

Week 6 at a glance

What this week hangs on the coat rack of week 1
what it is to remember
assumptions independent observations; a sampling distribution that is a bell big enough depends on how skewed
looking histogram, boxplot, mean next to median a tail drags the mean along
transforming log or square root for a tail to the right choose beforehand; convert H0H_0 too
ranks only the order counts a tie gets the mean
rank-sum test two independent groups μW=n1(n1+n2+1)2\mu_W = \dfrac{n_1(n_1+n_2+1)}{2}; r=|z|Nr = \dfrac{\lvert z \rvert}{\sqrt{N}}
signed-rank test two paired measurements leave out the zeros; μT+=n(n+1)4\mu_{T^+} = \dfrac{n(n+1)}{4}; r=|z|2nr = \dfrac{\lvert z \rvert}{\sqrt{2n}}
permutation test shuffle the group names, count the dots understand it, don’t run it
in R wilcox.test(), with paired = TRUE if it is paired R’s W is your W minus the smallest possible
Back to top