When there is no formula, or you doubt the one you have, let the computer repeat the study. This lesson builds a bootstrap interval and a permutation test for the birth weight gap, and shows where resampling fails.
This lesson follows Comparing two groups, where a t-test put a confidence interval and a p-value on the birth weight gap between smokers and non-smokers.
The idea: let the data stand in for the population
The t-test gets its interval from a formula. That formula assumes the mean of each group behaves like a normal distribution, and it only exists for a few statistics, such as a mean or a difference in means. Ask for a confidence interval for a difference in medians, or for the ratio of two SDs, and there is no simple formula to reach for.
Resampling replaces the formula with a computer experiment. You draw many new datasets from the one you have, calculate your statistic on each, and look at how much it varies. Two methods cover most needs:
- The bootstrap answers "how precise is my estimate?". It gives a standard error and a confidence interval.
- The permutation test answers "could this difference be chance?". It gives a p-value.
The bootstrap rests on one plain idea. You would like to know what would happen if you could repeat the study many times, drawing new mothers from the same population. You cannot. But your sample of 189 births is the best picture of that population you have. So you treat the sample as if it were the population, and draw from it instead.
Each new draw is a bootstrap resample: the same number of values as the original, picked at random with replacement. "With replacement" means each value goes back after it is picked, so it can be picked again. A resample of 115 non-smokers therefore contains some mothers twice or three times and leaves out about a third of them altogether. Every resample is a slightly different version of the data you might have collected, and the spread of the statistic across thousands of them estimates the spread you would see across repeated studies.
The code below uses bw, the labelled birth weight data made in Describing data, with smoke as a factor whose first level is "non-smoker".
non <- bw$bwt[bw$smoke == "non-smoker"]
smk <- bw$bwt[bw$smoke == "smoker"]
obs <- mean(non) - mean(smk)
obs
set.seed(42)
B <- 10000
boot_diff <- replicate(B, {
mean(sample(non, replace = TRUE)) - mean(sample(smk, replace = TRUE))
})
quantile(boot_diff, c(0.025, 0.975))
sd(boot_diff)
sum(boot_diff <= 0)
t.test(bwt ~ smoke, data = bw)$conf.intWhat this does, line by line
nonandsmkhold the birth weights of the two groups, 115 and 74 babies.obsis the observed difference in means, non-smoker minus smoker.set.seed(42)fixes R's random number generator, so you get exactly the same resamples, and the same numbers, every time you run the script.B <- 10000is the number of resamples.replicate(B, { … })runs the code in braces 10,000 times and collects the answers into a vector. Inside,sample(non, replace = TRUE)draws 115 values fromnonwith replacement, and the same happens for the smokers. Each group is resampled separately, so every resample keeps 115 non-smokers and 74 smokers, as in the study.quantile(boot_diff, c(0.025, 0.975))takes the values below which 2.5% and 97.5% of the bootstrap differences fall. The middle 95% is the percentile confidence interval.sd(boot_diff)is the bootstrap standard error: the SD of the estimate across resamples.sum(boot_diff <= 0)counts the resamples in which the gap vanished or reversed.- The last line prints the t-test's interval for comparison.
Reading the output. Non-smokers' babies were 284 g heavier on average, as in Comparing two groups. The bootstrap puts the 95% interval at 84 to 488 g, and the t-test at 79 to 489 g. The bootstrap standard error, 103 g, is close to the one the t-test uses. The two methods agree because the conditions for the t-test hold well here: the groups are fairly large and birth weight is roughly symmetric. That agreement is the expected result, and a useful check that the code is right.
If you draw a histogram of boot_diff with geom_histogram(), you see a smooth, roughly bell-shaped hump centred near 284 g. The percentile interval simply cuts 2.5% off each tail of that hump. Only 34 of the 10,000 resampled differences fall at or below zero, the count printed above, which is another way of seeing that the data point clearly to a positive gap.
Worked example · a bootstrap of five values
one resample: 3,100 · 3,100 · 3,400 · 3,900 · 2,900 → mean 3,280 g
another: 3,200 · 3,900 · 3,900 · 3,900 · 3,400 → mean 3,660 g
Step by step. The five values add to 16,500, so the mean is 3,300 g. In the first resample, 3,200 was never picked and 3,100 was picked twice; the total is 16,400 and the mean 3,280 g. In the second, 3,900 was picked three times and 2,900 and 3,100 not at all; the total is 18,300 and the mean 3,660 g. Repeat this thousands of times and the means pile up into a distribution. Its SD is the bootstrap standard error, and its 2.5th and 97.5th percentiles are the interval.
What the answer means. Resampling never invents new values. Every resample uses only the five numbers you measured. With five values there are only 126 different resamples (ignoring order), so the bootstrap distribution is lumpy, and it can never reach beyond 2,900 or 3,900 g.
A statistic with no simple formula: the median
The same code works for any statistic. Change mean to median and you have an interval for the difference in medians, which the t-test cannot give you.
median(non) - median(smk)
set.seed(42)
boot_med <- replicate(B, {
median(sample(non, replace = TRUE)) - median(sample(smk, replace = TRUE))
})
quantile(boot_med, c(0.025, 0.975))
length(unique(boot_med))Reading the output. The medians differ by 324.5 g, with a 95% bootstrap interval of about 38 to 659 g. That interval is about twice as wide as the one for the means. A median uses only the middle of the sorted values, so it carries less information about the centre than a mean when the data are roughly symmetric, and its interval is wider. The last line shows that the 10,000 resampled differences take only 731 distinct values: a median is always one of the recorded weights (or halfway between two), so the bootstrap distribution of a median is grainy.
Go deeper: the boot package and the BCa interval
The boot package, which comes with R, does the same job with more options. You write a function that takes the data and a vector of row numbers, and boot() calls it with resampled row numbers: diff_means <- function(d, i) { d <- d[i, ]; mean(d$bwt[d$smoke == "non-smoker"]) - mean(d$bwt[d$smoke == "smoker"]) }, then b <- boot(bw, diff_means, R = 10000, strata = bw$smoke). The strata argument resamples within each smoking group, as the hand-made version did.
With set.seed(42) first, it reports a standard error of 102.8 g and a bias of 1.9 g (the average bootstrap estimate minus the observed one, tiny here). boot.ci(b, type = c("perc", "bca")) gives a percentile interval of 81.6 to 488.3 g and a BCa (bias-corrected and accelerated) interval of 76.6 to 481.4 g. BCa adjusts the percentiles for bias and for skew in the bootstrap distribution, and it tends to be more accurate than the plain percentile interval when the distribution is lopsided. It needs more resamples to be stable, and for a symmetric case like this one the two barely differ.
The permutation test
A bootstrap estimates precision. A permutation test asks a different question: if smoking made no difference, how often would the labels alone produce a gap as large as 284 g?
The reasoning is direct. Under the null hypothesis, a baby's weight has nothing to do with whether its mother smoked. The labels "smoker" and "non-smoker" could then be swapped between babies without changing anything. So you shuffle them: keep the 189 weights where they are, deal out 74 "smoker" labels at random, and recalculate the difference. Each shuffle is one draw from the world in which smoking does not matter. Do it thousands of times and you have the null distribution of the difference, built from your own data rather than from a formula.
set.seed(42)
perm_diff <- replicate(B, {
shuffled <- sample(bw$smoke)
mean(bw$bwt[shuffled == "non-smoker"]) - mean(bw$bwt[shuffled == "smoker"])
})
range(perm_diff)
sum(abs(perm_diff) >= abs(obs))
(sum(abs(perm_diff) >= abs(obs)) + 1) / (B + 1)
t.test(bwt ~ smoke, data = bw)$p.value
t.test(bwt ~ smoke, data = bw, var.equal = TRUE)$p.valueWhat this does
sample(bw$smoke), withoutreplace = TRUE, returns the same 189 labels in a random order: still 115 non-smokers and 74 smokers, but attached to different babies. This is a permutation.- The difference in means is recalculated with the shuffled labels, 10,000 times.
range(perm_diff)shows how large the gap gets by chance alone.sum(abs(perm_diff) >= abs(obs))counts the shuffles that gave a gap at least as large as the real one, in either direction. Usingabs()makes the test two-sided, like the t-test.- The p-value adds 1 to the count and 1 to the number of shuffles. The extra 1 counts the real labelling, which is itself one of the possible arrangements, and it stops the p-value from ever being exactly 0.
Reading the output. Shuffled labels produced gaps from −423 to +396 g, so chance alone can occasionally do a lot. But only 100 of the 10,000 shuffles gave a gap of 284 g or more in either direction, and the permutation p-value is (100 + 1) ÷ (10,000 + 1) = 0.0101. Welch's t-test gave 0.0070 and the equal-variance (Student) t-test 0.0087. All three say the same thing: a gap this large would be unusual if smoking made no difference.
The permutation p-value sits closest to the Student version for a reason. Shuffling labels assumes that, under the null, the two groups are interchangeable: the same distribution, so also the same spread. That is the Student assumption, not Welch's. A permutation test is not assumption-free; its key assumption is exchangeability, meaning the labels could be swapped without changing anything if the null were true.
The smallest p-value a permutation test can report is 1 ÷ (B + 1). With 1,000 shuffles that is about 0.001, so a gene that would pass a strict multiple-testing cut-off, as in Multiple testing and power, can never do so. Choose the number of shuffles with the smallest p-value you might need in mind.
How many resamples?
Resampling adds its own randomness, called Monte Carlo error: run it again with a different seed and the last digits change. Here is the percentile interval for the mean difference with three different seeds, at two sizes:
- 10,000 resamples, seeds 1, 2 and 3: 82.7 to 486.6, 78.1 to 483.4 and 75.8 to 488.4 g.
- 1,000 resamples, the same seeds: 92.6 to 482.1, 80.3 to 489.6 and 59.2 to 488.6 g.
With 1,000 resamples the lower limit moved by more than 30 g from one seed to the next; with 10,000 it moved by about 7 g. The ends of an interval rest on the few resamples in the tails, so they need many resamples to settle. A sensible default is 10,000 for an interval or a p-value. If changing the seed changes your conclusion, you need more resamples, not a luckier seed. Always set a seed, and report it with the number of resamples, so others can reproduce your numbers exactly.
What resampling does not fix
Resampling frees you from a formula. It does not free you from the data. Two problems in particular pass straight through it.
Small samples
The bootstrap treats your sample as the population. With 189 births that is a good stand-in. With six it is not: six values rarely include the extremes of the real population, so the resamples vary too little and the interval is too narrow.
You can measure this. Treat the 189 birth weights as a whole population, whose mean you therefore know. Draw a sample of 6, compute a 95% percentile bootstrap interval from 2,000 resamples, and check whether it contains the true mean. Repeat 2,000 times. With set.seed(7), the bootstrap interval contained the true mean in only 86.7% of the samples, while the t-test interval from the same samples did so in 94.9%, close to the 95% it promises. At n = 6 the formula, with its allowance for small samples built into the t distribution, beats the bootstrap. Resampling is a tool for moderate and large samples, or for statistics with no formula, not a rescue for tiny ones.
Independence
Both methods resample or shuffle single observations, so both assume that observations are independent: one baby per mother here. If the data come in groups, such as several cells from each mouse or repeated measurements of each patient, resampling single values breaks the groups apart and treats related values as unrelated. The interval comes out too narrow and the p-value too small. The cure is to resample the independent units: whole mice, whole patients, whole donors. In Comparing two groups, the paired sleep data would need you to resample patients, keeping each patient's two values together, or to shuffle the drug labels within each patient.
Resampling also leaves bias untouched. If smokers in this study differed from non-smokers in weight or recorded race, the bootstrap will give a precise interval around a confounded difference. Adjusting for other factors is a job for the models of Linear models with groups and covariates.
The bootstrap was introduced by Bradley Efron in "Bootstrap methods: another look at the jackknife" (The Annals of Statistics, 1979). The BCa interval is from Efron 1987, "Better bootstrap confidence intervals" (Journal of the American Statistical Association). Permutation tests are older: R. A. Fisher described the idea of comparing an observed result with every rearrangement of the labels in The Design of Experiments (1935). The advice to add 1 to the count and to the number of shuffles is set out by Phipson and Smyth, "Permutation p-values should never be zero" (Statistical Applications in Genetics and Molecular Biology, 2010). The boot package accompanies Davison and Hinkley's book Bootstrap Methods and Their Application (Cambridge University Press, 1997).
Common mistakes
- Forgetting
replace = TRUEin a bootstrap. Without it,sample()only shuffles the values, every resample has the same mean, and the "interval" has zero width. - Resampling the two groups together without keeping their sizes. Resample within each group, or use
stratainboot(). - Reporting a p-value of 0 from a permutation test. The smallest honest value is 1 ÷ (B + 1).
- Trying several seeds and keeping the best one. Set the seed once, at the top of the script.
- Resampling cells, wells or repeated measurements as if they were independent. Resample the units that were randomised or sampled.
Further reading · Module 2Greenland et al. 2016: 25 common misreadings of p-values and confidence intervals. · All reading for this course
Check your understanding
1. What does sample(x, replace = TRUE) do in a bootstrap?
2. A permutation test with 10,000 shuffles finds no shuffled gap as large as the observed one. What p-value should you report?
3. You have 3 mice and 200 cells per mouse. Why is bootstrapping the 600 cells a problem?