Skip to content

Bootstrap Intervals & Permutation Tests

Resampling replaces a formula with a loop over your own data. The bootstrap draws the observations again with replacement and recomputes a statistic, which gives a confidence interval for quantities that have no textbook formula. A permutation test shuffles the group labels and recomputes the statistic, which gives a p-value without a model for the distribution. This page writes both as plain loops for a ratio of two means, repeats them with boot in R and SciPy in Python, and then shows three situations in which the loop runs and the answer is wrong.

Download cytokine_groups.csv and cells_per_donor.csv into your working directory. Both tables are invented.

cytokine_groups.csv has 36 rows, one per donor, and four columns: donor_id, group, il6_pg_ml, and crp_mg_l. Eighteen donors are controls and eighteen are patients, and each donor is one independent experimental unit. Serum IL-6 comes from a lognormal distribution with a median of 5 pg/mL in controls and 10 pg/mL in patients, with the same spread on the log scale in both groups. The true ratio of medians is 2, and with equal log-scale spread the true ratio of means is also 2. Inside each group, CRP has a true Spearman correlation of 0.68 with IL-6.

cells_per_donor.csv has 200 rows, one per cell, and two columns: donor_id and pstat3_au, a phospho-STAT3 fluorescence in arbitrary units. Eight donors contribute 25 cells each, and the true mean over the population of donors is 1000. The section on dependence uses it.

library(boot)
library(ggplot2)
library(patchwork)
set.seed(2026)
cytokines <- read.csv("cytokine_groups.csv")
dir.create("outputs", showWarnings = FALSE)
control <- cytokines$il6_pg_ml[cytokines$group == "control"]
patient <- cytokines$il6_pg_ml[cytokines$group == "patient"]
observed_ratio <- mean(patient) / mean(control)
for (group in c("control", "patient")) {
values <- cytokines$il6_pg_ml[cytokines$group == group]
cat(sprintf("%-7s n = %d, mean = %.2f, median = %.2f, max = %.2f\n",
group, length(values), mean(values), median(values),
max(values)))
}
cat(sprintf("Ratio of means, patient / control: %.3f\n", observed_ratio))
control n = 18, mean = 6.31, median = 4.73, max = 20.51
patient n = 18, mean = 12.01, median = 12.07, max = 21.77
Ratio of means, patient / control: 1.904

IL-6 is right-skewed. The control mean, 6.31 pg/mL, sits well above the control median, 4.73, because one control donor reads 20.51. The patient mean is 1.904 times the control mean. That fold change is the estimate, and a ratio of two means of skewed data from 18 donors per group has no simple textbook interval.

The uncertainty of the ratio is the amount by which it would vary if the study were repeated with new donors. New donors are not available, so the bootstrap uses the sample in place of the population. Draw 18 values from the 18 controls with replacement, do the same for the patients, and recompute the ratio. In one resample some donors appear twice and some not at all. After 9999 resamples, the spread of the 9999 ratios estimates the spread of the ratio across repeated studies.

Resample each group separately. The design fixed 18 donors per group, and the resampling repeats the design.

n_resamples <- 9999
boot_ratio <- numeric(n_resamples)
for (draw in seq_len(n_resamples)) {
resampled_control <- sample(control, replace = TRUE)
resampled_patient <- sample(patient, replace = TRUE)
boot_ratio[draw] <- mean(resampled_patient) / mean(resampled_control)
}
loop_interval <- quantile(boot_ratio, c(0.025, 0.975))
cat(sprintf("Bootstrap ratios from %.3f to %.3f\n", min(boot_ratio),
max(boot_ratio)))
cat(sprintf("%.1f%% of them are below the observed %.3f\n",
100 * mean(boot_ratio < observed_ratio), observed_ratio))
cat(sprintf("Bootstrap standard error %.3f\n", sd(boot_ratio)))
cat(sprintf("Percentile 95%% CI [%.3f, %.3f]\n", loop_interval[1],
loop_interval[2]))
Bootstrap ratios from 0.913 to 4.250
49.0% of them are below the observed 1.904
Bootstrap standard error 0.435
Percentile 95% CI [1.270, 2.965]

In R the resampled ratios run from 0.913 to 4.250. Their standard deviation, 0.435, is the bootstrap standard error of the ratio. The percentile interval takes the 2.5% and 97.5% quantiles of the 9999 ratios, 1.270 to 2.965. It contains the true ratio of 2. It is not symmetric around 1.904: the upper limit lies 1.06 above the estimate and the lower limit 0.63 below it, which fits a ratio that cannot go below zero.

Python draws other resamples from its own generator and prints 1.267 to 2.965. A new seed in one language moves the limits by a similar amount, so report no more digits than survive a change of seed.

boot() in R takes the table, a statistic function, and the number of resamples. The statistic function receives the table and the row numbers of one resample, and strata keeps each resample inside its group. boot.ci() then computes intervals from the stored resamples. In Python, scipy.stats.bootstrap() takes the two samples as a tuple, resamples each one separately, and passes them to the statistic function. A second call with bootstrap_result computes another interval type from the same resamples.

Both tools offer two kinds of interval. The percentile interval is the one from the loop. The bias-corrected and accelerated interval, BCa, also reads two quantiles of the bootstrap distribution, but it moves away from the 2.5% and 97.5% levels by two corrections. The bias correction comes from the share of resampled ratios below the observed ratio, which was 49.0% in the R loop and 48.5% in the Python loop, where a centered distribution gives 50%. The acceleration comes from the influence of each single donor on the ratio, and it accounts for a standard error that changes with the size of the ratio.

#' Ratio of the patient mean to the control mean of IL-6.
#'
#' @param data A data frame with the columns group and il6_pg_ml.
#' @param rows The row numbers that boot() drew for one resample.
#' @return The patient mean divided by the control mean in those rows.
MeanRatio <- function(data, rows) {
drawn <- data[rows, ]
mean(drawn$il6_pg_ml[drawn$group == "patient"]) /
mean(drawn$il6_pg_ml[drawn$group == "control"])
}
ratio_boot <- boot(cytokines, MeanRatio, R = 9999,
strata = factor(cytokines$group))
ratio_ci <- boot.ci(ratio_boot, type = c("perc", "bca"))
cat(sprintf("Ratio of means %.3f\n", ratio_boot$t0))
cat(sprintf("Percentile 95%% CI [%.3f, %.3f]\n", ratio_ci$percent[4],
ratio_ci$percent[5]))
cat(sprintf("BCa 95%% CI [%.3f, %.3f]\n", ratio_ci$bca[4],
ratio_ci$bca[5]))
Ratio of means 1.904
Percentile 95% CI [1.264, 2.991]
BCa 95% CI [1.221, 2.889]

The percentile limits of the library calls, 1.264 to 2.991 in R and 1.276 to 3.005 in Python, repeat the loop within resampling noise. The BCa limits are lower at both ends: 1.221 to 2.889 in R and 1.216 to 2.858 in Python. Both intervals contain 2.

BCa is the default of SciPy and of DABEST, which the Estimation Statistics page uses for group comparisons. For a smooth statistic such as a ratio of means, its coverage error shrinks faster with the sample size than that of the percentile interval. A median changes in jumps as values enter and leave a resample, and the corrections are unreliable for it, so use the percentile interval for a median.

The Correlation page reports Spearman’s rho without an interval, because neither cor.test() nor spearmanr() returns one. The bootstrap supplies it. The resampled unit is the donor, so each resample draws whole rows, and a donor brings its IL-6 and its CRP together. Resampling the two columns separately breaks the pairs and removes the correlation that the interval is about.

In boot() the statistic function indexes both columns with the same rows. In SciPy, paired=True does the same. The code uses the 18 patients alone, because a pooled table mixes the correlation inside a group with the difference between the groups.

#' Spearman's rho between IL-6 and CRP in one resample of the rows.
#'
#' @param data A data frame with the columns il6_pg_ml and crp_mg_l.
#' @param rows The row numbers that boot() drew for one resample.
#' @return Spearman's rho of the two columns in those rows.
SpearmanRho <- function(data, rows) {
cor(data$il6_pg_ml[rows], data$crp_mg_l[rows], method = "spearman")
}
patients <- cytokines[cytokines$group == "patient", ]
rho_boot <- boot(patients, SpearmanRho, R = 9999)
rho_ci <- boot.ci(rho_boot, type = c("perc", "bca"))
cat(sprintf("Spearman rho %.3f in %d patients\n", rho_boot$t0,
nrow(patients)))
cat(sprintf("Percentile 95%% CI [%.3f, %.3f]\n", rho_ci$percent[4],
rho_ci$percent[5]))
cat(sprintf("BCa 95%% CI [%.3f, %.3f]\n", rho_ci$bca[4],
rho_ci$bca[5]))
Spearman rho 0.513 in 18 patients
Percentile 95% CI [-0.002, 0.852]
BCa 95% CI [-0.024, 0.842]

Rho is 0.513 among the 18 patients, against a true value of 0.68. The percentile interval runs from -0.002 to 0.852 in R and from -0.022 to 0.851 in Python, and BCa moves both limits down by 0.03 or less. Eighteen donors leave rho almost open: the data are compatible with no monotone association and with a strong one. Report that width with the coefficient.

A permutation test asks a different question: can the group labels alone produce a ratio this far from 1? Suppose the labels carry no information, so that IL-6 has one distribution in both groups. Then the 36 values are exchangeable, and every way to call 18 of them “patient” was equally likely. Shuffle the labels, recompute the statistic, and repeat. The shuffled statistics form the null distribution, and the p-value is the share of that distribution at least as extreme as the observed statistic.

The statistic here is the log of the ratio of means. On the log scale a ratio of 2 and a ratio of 0.5 lie at the same distance from zero, so “as extreme” is a comparison of absolute values.

The p-value is (b + 1) / (B + 1), where b counts the extreme shuffles among B. The observed labeling is one of the possible arrangements, so it belongs in both counts. Without the added one, a run with no extreme shuffle reports p = 0, which a finite number of shuffles cannot support, and the test rejects a true null too often.

pooled <- c(patient, control)
first <- seq_along(patient)
observed_log <- log(mean(patient) / mean(control))
perm_log <- numeric(n_resamples)
for (draw in seq_len(n_resamples)) {
shuffled <- sample(pooled)
perm_log[draw] <- log(mean(shuffled[first]) / mean(shuffled[-first]))
}
as_extreme <- sum(abs(perm_log) >= abs(observed_log))
cat(sprintf("Observed log ratio %.3f\n", observed_log))
cat(sprintf("Shuffled log ratios from %.3f to %.3f\n", min(perm_log),
max(perm_log)))
cat(sprintf("%d of %d shuffles are as extreme\n", as_extreme, n_resamples))
cat(sprintf("p = (%d + 1) / (%d + 1) = %.4f\n", as_extreme, n_resamples,
(as_extreme + 1) / (n_resamples + 1)))
Observed log ratio 0.644
Shuffled log ratios from -0.725 to 0.828
44 of 9999 shuffles are as extreme
p = (44 + 1) / (9999 + 1) = 0.0045

The observed log ratio is 0.644. In R, 44 of 9999 shuffles reach it in absolute value, so p = 45 / 10000 = 0.0045. Python counts 42 and prints 0.0043. This p-value is a tail probability under the null of exchangeable labels. It is not the probability that the groups are the same, and it does not measure the difference. The size of the difference is the ratio of 1.904 with its bootstrap interval.

State the null hypothesis exactly, because it is stronger than “equal means” or “equal medians”. A label shuffle is justified when the two groups have the same distribution: the same center, the same spread, and the same shape. A small p-value says that the distributions differ in some way that the statistic responds to. It does not say in which way. Two groups with equal medians and unequal spreads are not exchangeable, and a label permutation test of their difference in medians does not keep its 5% error rate, even in large samples, as Chung and Romano (2013) show.

scipy.stats.permutation_test() runs the same shuffle. permutation_type="independent" moves observations between the two samples, which is the label shuffle of the loop. This library call is in Python only, and the loop above is the R method on this page.

def log_mean_ratio(patient_values, control_values, axis=-1):
"""Compute the log of the ratio of two group means.
Args:
patient_values: IL-6 values labeled as patient.
control_values: IL-6 values labeled as control.
axis: The axis that holds the donors.
Returns:
The log of the patient mean divided by the control mean.
"""
return np.log(mean_ratio(patient_values, control_values, axis=axis))
permutation = stats.permutation_test(
(patient, control), log_mean_ratio, permutation_type="independent",
n_resamples=9999, alternative="two-sided", rng=rng)
print(f"Observed log ratio {permutation.statistic:.3f}, "
f"p = {permutation.pvalue:.4f}")
Observed log ratio 0.644, p = 0.0054

SciPy prints p = 0.0054. It computes each one-sided p-value as (b + 1) / (B + 1) and returns twice the smaller one, where the loop counts both tails by absolute value. The two conventions estimate the same probability when the null distribution is symmetric, as it is for equal group sizes.

The three p-values, 0.0043, 0.0045 and 0.0054, also come from three different sets of 9999 shuffles. With a p-value near 0.005, the count of extreme shuffles among 9999 has a standard deviation of about 7, so the three values are one result. Use more shuffles when a p-value close to a threshold must be stable.

The two loops left two vectors, boot_ratio and perm_log. A histogram of each shows what the interval and the p-value summarize.

boot_panel <- ggplot(data.frame(ratio = boot_ratio), aes(ratio)) +
geom_histogram(bins = 60, fill = "#69b3a2", color = "white") +
geom_vline(xintercept = observed_ratio, color = "#1f4e5f") +
geom_vline(xintercept = loop_interval, color = "#1f4e5f",
linetype = "dashed") +
labs(title = "Bootstrap", x = "Ratio of means, patient / control",
y = "Resamples") +
theme_classic(base_size = 12)
perm_panel <- ggplot(data.frame(log_ratio = perm_log), aes(log_ratio)) +
geom_histogram(bins = 60, fill = "grey70", color = "white") +
geom_vline(xintercept = c(-1, 1) * abs(observed_log),
color = "#d95f02") +
labs(title = "Permutation", x = "Log ratio of means after a shuffle",
y = "Shuffles") +
theme_classic(base_size = 12)
ggsave("outputs/resampling-distributions-r.png", boot_panel + perm_panel,
width = 9, height = 4, dpi = 150)

Two histograms drawn with ggplot2. Left, the bootstrap distribution of the ratio of means, right-skewed, with a solid line at the observed ratio of 1.90 and dashed lines at the percentile limits of 1.27 and 2.97. Right, the permutation distribution of the log ratio, centered on zero, with lines at plus and minus 0.644 that leave only the thin tails outside.

The bootstrap distribution is centered near the observed ratio, the solid line, and has a longer right tail. The dashed lines are the percentile limits. The permutation distribution is centered on zero, the value of the log ratio when the labels carry no information. Its two lines mark the observed log ratio and its mirror image, and the p-value is the share of the histogram beyond them. One histogram is centered on the estimate and the other on the null value, and that is the difference between an interval and a test.

The bootstrap can only reuse the values it has. With 5 donors in a group, a resample holds one of 126 distinct sets of values, and none contains a value beyond the observed range. The resamples then vary less than new samples from the population do, and the interval comes out too narrow.

One interval cannot show this, so the code does two steps. It computes the percentile interval for the first five donors of each group. Then it uses the known truth: it draws 2000 new experiments from the two lognormal distributions that generated the table, computes a percentile interval in each one, and counts the intervals that contain the true ratio of 2.

#' Percentile bootstrap interval for a ratio of two group means.
#'
#' @param numerator Values of the group in the numerator.
#' @param denominator Values of the group in the denominator.
#' @param n_draws The number of bootstrap resamples.
#' @return The 2.5% and 97.5% quantiles of the resampled ratio.
RatioInterval <- function(numerator, denominator, n_draws) {
top <- matrix(sample(numerator, n_draws * length(numerator),
replace = TRUE), nrow = n_draws)
bottom <- matrix(sample(denominator, n_draws * length(denominator),
replace = TRUE), nrow = n_draws)
quantile(rowMeans(top) / rowMeans(bottom), c(0.025, 0.975))
}
five <- RatioInterval(patient[1:5], control[1:5], 9999)
cat(sprintf("First 5 donors per group: ratio %.3f, 95%% CI [%.3f, %.3f]\n",
mean(patient[1:5]) / mean(control[1:5]), five[1], five[2]))
n_experiments <- 2000
for (size in c(5, 18)) {
covered <- 0
for (experiment in seq_len(n_experiments)) {
limits <- RatioInterval(rlnorm(size, log(10), 0.7),
rlnorm(size, log(5), 0.7), 999)
covered <- covered + (limits[1] <= 2 && limits[2] >= 2)
}
cat(sprintf("n = %2d per group: %.1f%% of %d intervals contain 2\n",
size, 100 * covered / n_experiments, n_experiments))
}
First 5 donors per group: ratio 2.329, 95% CI [1.459, 4.252]
n = 5 per group: 87.3% of 2000 intervals contain 2
n = 18 per group: 92.7% of 2000 intervals contain 2

The interval from five donors per group, 1.459 to 4.252 in R, contains 2 and looks like any other interval. The simulation shows what its 95% label is worth. With 5 donors per group, 87.3% of the intervals contain the true ratio in R and 86.2% in Python, so the interval misses about 13% of the time where it claims 5%. With 18 donors per group the coverage is 92.7% and 91.4%, closer to 95% and still short of it.

More resamples do not repair this, because the limit is the 5 values and not the 9999 draws. Read a bootstrap interval from a small sample as too narrow, and prefer a larger sample to a finer bootstrap.

The bootstrap treats the resampled items as independent draws from the population. In cells_per_donor.csv the cells of one donor share the level of that donor, so 200 cells are not 200 independent observations. A claim about the mean pSTAT3 signal in people is a claim about donors, and the donor is the experimental unit. The code builds the interval for the mean in two ways. The first resamples the 200 cells. The second resamples the 8 donors and keeps all 25 cells of each donor that it draws.

cells <- read.csv("cells_per_donor.csv")
by_donor <- split(cells$pstat3_au, cells$donor_id)
cell_means <- numeric(n_resamples)
donor_means <- numeric(n_resamples)
for (draw in seq_len(n_resamples)) {
cell_means[draw] <- mean(sample(cells$pstat3_au, replace = TRUE))
drawn_donors <- sample(names(by_donor), replace = TRUE)
donor_means[draw] <- mean(unlist(by_donor[drawn_donors]))
}
cell_interval <- quantile(cell_means, c(0.025, 0.975))
donor_interval <- quantile(donor_means, c(0.025, 0.975))
cat(sprintf("%d cells from %d donors, mean %.1f\n", nrow(cells),
length(by_donor), mean(cells$pstat3_au)))
cat(sprintf("Resample cells: 95%% CI [%.1f, %.1f], width %.1f\n",
cell_interval[1], cell_interval[2], diff(cell_interval)))
cat(sprintf("Resample donors: 95%% CI [%.1f, %.1f], width %.1f\n",
donor_interval[1], donor_interval[2], diff(donor_interval)))
200 cells from 8 donors, mean 944.1
Resample cells: 95% CI [909.0, 978.9], width 69.9
Resample donors: 95% CI [825.2, 1052.6], width 227.4

The mean is 944.1 in both cases. In R, resampling cells gives 909.0 to 978.9, a width of 69.9. Resampling donors gives 825.2 to 1052.6, a width of 227.4, which is more than three times wider. The true mean is 1000: the donor interval contains it, and the cell interval does not.

The cell bootstrap answers how well 200 cells determine the mean of these 8 donors. The donor bootstrap answers how well 8 donors determine the mean of the population, and that is the question of the experiment. With 8 donors the second interval is itself a small-sample interval, and the section above shows that such an interval tends to be too narrow. The mixed models page fits the same structure with a donor term.

The bootstrap suits a statistic that depends on the bulk of the sample. A maximum depends on one value. No resample can hold a value above the largest observed one, so the bootstrap distribution of the maximum stops there.

boot_max <- numeric(n_resamples)
for (draw in seq_len(n_resamples)) {
boot_max[draw] <- max(sample(patient, replace = TRUE))
}
max_interval <- quantile(boot_max, c(0.025, 0.975))
cat(sprintf("Largest patient value %.2f pg/mL\n", max(patient)))
cat(sprintf("%.1f%% of resamples have exactly that maximum\n",
100 * mean(boot_max == max(patient))))
cat(sprintf("Percentile 95%% CI [%.2f, %.2f]\n", max_interval[1],
max_interval[2]))
cat(sprintf("%.1f%% of the simulated patient population is above %.2f\n",
100 * plnorm(max(patient), log(10), 0.7, lower.tail = FALSE),
max(patient)))
Largest patient value 21.77 pg/mL
64.0% of resamples have exactly that maximum
Percentile 95% CI [19.80, 21.77]
13.3% of the simulated patient population is above 21.77

The largest patient value is 21.77 pg/mL, and 64.0% of the R resamples have exactly that maximum. A resample of 18 includes a given donor with probability 1 - (17/18)^18, which is 64.3%. The interval, 19.80 to 21.77, takes the observed maximum as its upper limit, as if no patient could exceed it. In the population that generated the table, 13.3% of patients do.

A minimum fails in the same way, and so does an extreme quantile, such as the 99th percentile of 18 values.

Give the estimate, the type of interval, the number of resamples, the unit that was resampled, and the software: “Mean serum IL-6 was 1.90 times higher in patients than in controls (95% BCa bootstrap CI 1.22 to 2.89; 9999 resamples of donors within each group, boot 1.3-32). A label permutation test of the log ratio of means gave p = 0.0045 (9999 shuffles).” Keep the seed in the analysis code, so that a reader can reproduce the limits.

Efron, 1979 introduces the bootstrap, which estimates the sampling distribution of a statistic from resamples of the data.

Efron, 1987 describes the bias-corrected and accelerated bootstrap interval.

The boot package by Canty and Ripley implements in R the bootstrap methods of the book by Davison and Hinkley, 1997.

Phipson and Smyth, 2010 explain why a permutation p-value from random shuffles counts the observed arrangement and is never zero.

Chung and Romano, 2013 show that a permutation test of equal means or equal medians can miss its error rate when the two distributions differ in other respects, and they construct a test that keeps it in large samples.

Hesterberg, 2015 reviews the bootstrap and permutation tests for teachers of statistics, with the small-sample behavior of each interval type.

The SciPy bootstrap reference documents the paired, method and bootstrap_result arguments, and the “basic” interval that this page does not use.

The SciPy permutation_test reference describes the three permutation types, the exact test that SciPy runs when all arrangements can be listed, and its convention for a two-sided p-value.

The boot.ci reference lists the five interval types of boot, including the studentized interval, which needs a variance estimate for each resample.

The Estimation Statistics page applies BCa bootstrap intervals to group comparisons and draws the bootstrap distribution beside the data. The Correlation page covers Spearman’s rho itself.

The multiple testing page matters when one permutation test runs for each of many genes, because the smallest possible p-value, 1 / (B + 1), limits what a correction can declare.