Paired Samples: Paired t-test & Wilcoxon Signed-rank
When the same donor, animal, or tissue sample is measured under two conditions, the two columns of numbers are not two independent groups. Each row is one experimental unit with its own baseline, and the question is how much that unit changed. This page analyzes the within-pair differences of a cytokine assay with a paired t-test and a Wilcoxon signed-rank test, in R and Python. It also runs an unpaired test on the same numbers to show what that mistake costs.
The pair is the experimental unit
Section titled “The pair is the experimental unit”A paired design gives two values per unit: TNF from a control and a stimulated culture of one donor’s cells, a transcript in tumor and matched normal tissue from one patient, a body weight before and after a diet in one mouse. The two values share everything that makes that unit different from the others, such as its genetics, its age, and the state of the cells on the day of the draw.
Subtracting one value from the other removes the shared part. Eighteen donors give 18 differences, and the sample size of the analysis is 18, not 36. Every method on this page is a one-sample method applied to that single column of differences. For two groups made of different units, use the two-group tests page.
Get the data
Section titled “Get the data”Download tnf_paired_donors.csv into your working directory. The invented table has 18 rows, one per blood donor, and three columns: donor_id, control_pg_ml, and stimulated_pg_ml. The cells of each donor were split into two cultures, one in medium alone and one with a candidate adjuvant, and TNF was measured in each supernatant in pg/mL.
The values come from a simulation with known answers. Control values differ widely between donors; they are lognormal with a median of 400 pg/mL. The adjuvant adds a change with a true mean of +40 pg/mL and a standard deviation of 45 pg/mL, whatever the baseline. The assay reports each concentration to the nearest 5 pg/mL, which matters for the rank test further down.
The first block also defines a function that prints a t-test on one line, because the page compares three of them.
library(ggplot2)library(patchwork)
tnf <- read.csv("tnf_paired_donors.csv")dir.create("outputs", showWarnings = FALSE)cat(sprintf("%d donors, columns: %s\n", nrow(tnf), paste(names(tnf), collapse = ", ")))
#' Print the statistic, the p-value and the interval of a t-test.#'#' @param label A short name for the test.#' @param test An htest object from t.test().#' @return Invisibly, the test object.ReportTTest <- function(label, test) { cat(sprintf("%-18s t = %.3f, df = %.2f, p = %.4f, 95%% CI [%.2f, %.2f]\n", label, test$statistic, test$parameter, test$p.value, test$conf.int[1], test$conf.int[2])) invisible(test)}18 donors, columns: donor_id, control_pg_ml, stimulated_pg_mlfrom pathlib import Path
import matplotlib.pyplot as pltimport numpy as npimport pandas as pdfrom scipy import stats
tnf = pd.read_csv("tnf_paired_donors.csv")output = Path("outputs")output.mkdir(exist_ok=True)print(f"{len(tnf)} donors, columns: {', '.join(tnf.columns)}")
def report_t_test(label, test): """Print the statistic, the p-value and the interval of a t-test.
Args: label: A short name for the test. test: A result object from a SciPy t-test function.
Returns: The 95% confidence interval of the test. """ interval = test.confidence_interval(0.95) print(f"{label:<18} t = {test.statistic:.3f}, df = {test.df:.2f}, " f"p = {test.pvalue:.4f}, " f"95% CI [{interval.low:.2f}, {interval.high:.2f}]") return interval18 donors, columns: donor_id, control_pg_ml, stimulated_pg_mlCompute the within-pair differences
Section titled “Compute the within-pair differences”Subtract in one direction and keep it for the whole analysis. Here the difference is stimulated minus control, so a positive value is an increase in TNF.
difference <- tnf$stimulated_pg_ml - tnf$control_pg_mlcat(sprintf("Control: mean %.2f, SD %.2f\n", mean(tnf$control_pg_ml), sd(tnf$control_pg_ml)))cat(sprintf("Stimulated: mean %.2f, SD %.2f\n", mean(tnf$stimulated_pg_ml), sd(tnf$stimulated_pg_ml)))cat(sprintf("Difference: mean %.2f, SD %.2f\n", mean(difference), sd(difference)))cat(sprintf("Correlation of the two columns: %.3f\n", cor(tnf$control_pg_ml, tnf$stimulated_pg_ml)))cat(sprintf("%d increases, %d decreases, %d unchanged\n", sum(difference > 0), sum(difference < 0), sum(difference == 0)))Control: mean 419.44, SD 134.80Stimulated: mean 461.11, SD 136.14Difference: mean 41.67, SD 46.05Correlation of the two columns: 0.94214 increases, 3 decreases, 1 unchangeddifference = tnf["stimulated_pg_ml"] - tnf["control_pg_ml"]print(f"Control: mean {tnf['control_pg_ml'].mean():.2f}, " f"SD {tnf['control_pg_ml'].std():.2f}")print(f"Stimulated: mean {tnf['stimulated_pg_ml'].mean():.2f}, " f"SD {tnf['stimulated_pg_ml'].std():.2f}")print(f"Difference: mean {difference.mean():.2f}, " f"SD {difference.std():.2f}")correlation = tnf["control_pg_ml"].corr(tnf["stimulated_pg_ml"])print(f"Correlation of the two columns: {correlation:.3f}")print(f"{(difference > 0).sum()} increases, {(difference < 0).sum()} " f"decreases, {(difference == 0).sum()} unchanged")Control: mean 419.44, SD 134.80Stimulated: mean 461.11, SD 136.14Difference: mean 41.67, SD 46.05Correlation of the two columns: 0.94214 increases, 3 decreases, 1 unchangedThe two columns have almost the same spread, 134.80 and 136.14 pg/mL, and a correlation of 0.942. A donor with a high control value also has a high stimulated value. The differences have a standard deviation of 46.05 pg/mL, about a third of either column.
That drop is the gain of a paired design. The variance of a difference is the sum of the two variances minus twice the covariance, and a correlation of 0.942 removes most of that sum.
Look at the differences
Section titled “Look at the differences”The paired t-test assumes that the differences are independent of each other and that their mean is close to normally distributed. It assumes nothing about the shape of the control column or of the stimulated column. Draw the differences, because that column is the one the test uses.
long <- data.frame( donor_id = rep(tnf$donor_id, times = 2), condition = factor(rep(c("Control", "Stimulated"), each = nrow(tnf)), levels = c("Control", "Stimulated")), tnf_pg_ml = c(tnf$control_pg_ml, tnf$stimulated_pg_ml))paired <- t.test(tnf$stimulated_pg_ml, tnf$control_pg_ml, paired = TRUE)estimate <- data.frame(position = 1.5, mean = mean(difference), low = paired$conf.int[1], high = paired$conf.int[2])
lines_panel <- ggplot(long, aes(condition, tnf_pg_ml, group = donor_id)) + geom_line(color = "grey55") + geom_point(color = "#1f4e5f", size = 1.8) + labs(x = NULL, y = "TNF (pg/mL)", title = "One line per donor") + theme_classic(base_size = 12)difference_panel <- ggplot(data.frame(difference), aes(1, difference)) + geom_hline(yintercept = 0, linetype = "dashed", color = "grey40") + geom_point(position = position_jitter(width = 0.12, height = 0, seed = 1), color = "#69b3a2", size = 2) + geom_pointrange(data = estimate, aes(position, mean, ymin = low, ymax = high), color = "#1f4e5f", linewidth = 0.9) + scale_x_continuous(limits = c(0.6, 1.9), breaks = c(1, 1.5), labels = c("Each donor", "Mean, 95% CI")) + labs(x = NULL, y = "Stimulated minus control (pg/mL)", title = "Within-pair differences") + theme_classic(base_size = 12)ggsave("outputs/paired-differences-r.png", lines_panel + difference_panel, width = 8, height = 4, dpi = 150)
paired = stats.ttest_rel(tnf["stimulated_pg_ml"], tnf["control_pg_ml"])paired_interval = paired.confidence_interval(0.95)jitter = np.random.default_rng(1).uniform(-0.12, 0.12, len(difference))
figure, (lines_axes, difference_axes) = plt.subplots(1, 2, figsize=(8, 4))for row in tnf.itertuples(): lines_axes.plot([0, 1], [row.control_pg_ml, row.stimulated_pg_ml], color="0.55", marker="o", markerfacecolor="#1f2a44", markeredgecolor="#1f2a44", markersize=4)lines_axes.set_xticks([0, 1], ["Control", "Stimulated"])lines_axes.set_xlim(-0.3, 1.3)lines_axes.set_ylabel("TNF (pg/mL)")lines_axes.set_title("One line per donor")
difference_axes.axhline(0, color="0.4", linestyle="--")difference_axes.scatter(1 + jitter, difference, color="#4c72b0", s=25)difference_axes.errorbar( 1.5, difference.mean(), yerr=[[difference.mean() - paired_interval.low], [paired_interval.high - difference.mean()]], color="#1f2a44", marker="o", linewidth=2)difference_axes.set_xticks([1, 1.5], ["Each donor", "Mean, 95% CI"])difference_axes.set_xlim(0.6, 1.9)difference_axes.set_ylabel("Stimulated minus control (pg/mL)")difference_axes.set_title("Within-pair differences")figure.tight_layout()figure.savefig(output / "paired-differences-python.png", dpi=150)plt.close(figure)
On the left, the donors start far apart, and one donor sits far above the rest. The shape of either column, skewed or not, has no bearing on the paired analysis. On the right, the differences scatter around their mean with no long tail: 14 increases, 3 decreases, and one donor with no change. No single donor sets the mean.
Paired t-test
Section titled “Paired t-test”t.test(..., paired = TRUE) in R and ttest_rel() in SciPy take the two columns. A one-sample t-test of the differences against zero is the same calculation, and the output shows it.
one_sample <- t.test(difference, mu = 0)ReportTTest("Paired t-test", paired)ReportTTest("One-sample t-test", one_sample)Paired t-test t = 3.839, df = 17.00, p = 0.0013, 95% CI [18.77, 64.57]One-sample t-test t = 3.839, df = 17.00, p = 0.0013, 95% CI [18.77, 64.57]one_sample = stats.ttest_1samp(difference, 0)report_t_test("Paired t-test", paired)report_t_test("One-sample t-test", one_sample)Paired t-test t = 3.839, df = 17.00, p = 0.0013, 95% CI [18.77, 64.57]One-sample t-test t = 3.839, df = 17.00, p = 0.0013, 95% CI [18.77, 64.57]The two lines are identical: t = 3.839 on 17 degrees of freedom, one fewer than the number of pairs. The estimate is the mean difference of 41.67 pg/mL, and mean changes from 18.77 to 64.57 pg/mL are compatible with these 18 donors. That interval contains the true value of the simulation, +40 pg/mL.
The p-value of 0.0013 says that a mean change of zero fits the differences poorly. It does not say how large the change is. The interval does.
What an unpaired test does to the same numbers
Section titled “What an unpaired test does to the same numbers”Welch’s t-test treats the two columns as 18 donors and 18 other donors. Run it on the same table and compare the standard error of each analysis.
welch <- t.test(tnf$stimulated_pg_ml, tnf$control_pg_ml)ReportTTest("Paired t-test", paired)ReportTTest("Welch t-test", welch)cat(sprintf("Standard error: paired %.2f, Welch %.2f\n", paired$stderr, welch$stderr))Paired t-test t = 3.839, df = 17.00, p = 0.0013, 95% CI [18.77, 64.57]Welch t-test t = 0.923, df = 34.00, p = 0.3627, 95% CI [-50.10, 133.44]Standard error: paired 10.85, Welch 45.16welch = stats.ttest_ind(tnf["stimulated_pg_ml"], tnf["control_pg_ml"], equal_var=False)report_t_test("Paired t-test", paired)report_t_test("Welch t-test", welch)paired_error = difference.std() / np.sqrt(len(difference))welch_error = np.sqrt(tnf["stimulated_pg_ml"].var() / len(tnf) + tnf["control_pg_ml"].var() / len(tnf))print(f"Standard error: paired {paired_error:.2f}, Welch {welch_error:.2f}")Paired t-test t = 3.839, df = 17.00, p = 0.0013, 95% CI [18.77, 64.57]Welch t-test t = 0.923, df = 34.00, p = 0.3627, 95% CI [-50.10, 133.44]Standard error: paired 10.85, Welch 45.16The point estimate does not move, because the difference of the two means equals the mean of the differences, 41.67 pg/mL. The standard error grows from 10.85 to 45.16 pg/mL, so the Welch interval, −50.10 to 133.44 pg/mL, is about four times as wide as the paired one and includes zero.
Welch’s test measures the 41.67 pg/mL shift against the spread between donors, about 135 pg/mL in each column, as if different donors had supplied each column. The paired analysis measures the same shift against the spread of the within-donor changes, 46.05 pg/mL. The donors did not become less variable. The subtraction took the donor-to-donor variance out of the comparison.
The unpaired standard error is wrong for this design because its formula assumes two independent samples, and these two columns have a correlation of 0.942. The sign of that correlation sets the direction of the error. A positive correlation, the usual case when one unit is measured twice, makes the unpaired interval too wide. A negative correlation makes it too narrow.
The opposite mistake is to pair values that the design never paired. If 18 donors supplied the control cultures and 18 other donors the stimulated ones, row 1 of one column has no partner in the other, and each “difference” depends on the order of the rows. Shuffle one column and the paired result changes. Sort both columns, which a spreadsheet does in one click, and the largest value meets the largest and the smallest meets the smallest, so the differences vary much less and the interval shrinks below what the data support. Pair only what the experiment paired before any value was measured.
Wilcoxon signed-rank test
Section titled “Wilcoxon signed-rank test”The signed-rank test ranks the absolute differences and sums the ranks that belong to positive differences. Its null hypothesis is that the distribution of the differences is symmetric about zero. That is a different question from the one the t-test asks about the mean difference. A center away from zero can reject the signed-rank null, and so can a skewed set of differences whose mean is zero.
Choose between the two tests by the question, before you see the data. Do not run a normality test on 18 differences and let its p-value pick the method; the assumptions page explains why a diagnostic p-value does not select the test.
Ties and zeros force a decision, and software does not agree on it. The rounding to 5 pg/mL left two donors with a difference of 65, a −20 and a 20 with the same absolute size, a −30 and a 30, and one donor with a difference of exactly zero. A zero has no sign, so it belongs to neither rank sum. Wilcoxon’s procedure drops the zeros before ranking. Pratt’s procedure ranks every absolute difference, zeros included, and then drops the ranks of the zeros.
cat(sprintf("Sorted differences: %s\n", paste(sort(difference), collapse = " ")))signed_rank <- wilcox.test(difference, conf.int = TRUE)cat(sprintf("Exact, zero ranked: V = %.0f, p = %.4f\n", signed_rank$statistic, signed_rank$p.value))cat(sprintf("Pseudomedian %.1f pg/mL, %.1f%% CI [%.1f, %.1f]\n", signed_rank$estimate, 100 * attr(signed_rank$conf.int, "conf.level"), signed_rank$conf.int[1], signed_rank$conf.int[2]))approximate <- wilcox.test(difference, exact = FALSE)cat(sprintf("Normal approximation, zero dropped: V = %.0f, p = %.4f\n", approximate$statistic, approximate$p.value))Sorted differences: -30 -25 -20 0 5 10 20 30 40 45 65 65 70 75 80 85 110 125Exact, zero ranked: V = 152, p = 0.0020Pseudomedian 42.5 pg/mL, 95.6% CI [20.0, 67.5]Normal approximation, zero dropped: V = 138, p = 0.0039values = difference.to_numpy()ordered = " ".join(str(value) for value in sorted(values))print(f"Sorted differences: {ordered}")default = stats.wilcoxon(values)print(f"Default, zero dropped: T = {default.statistic:.0f}, " f"p = {default.pvalue:.4f}")exact = stats.wilcoxon(values, zero_method="pratt", method=stats.PermutationMethod(n_resamples=2**18))print(f"Exact, zero ranked: T = {exact.statistic:.0f}, " f"p = {exact.pvalue:.4f}")corrected = stats.wilcoxon(values, method="asymptotic", correction=True)print("Normal approximation with correction: " f"T = {corrected.statistic:.0f}, " f"p = {corrected.pvalue:.4f}")walsh = np.add.outer(values, values)[np.triu_indices(len(values))] / 2print(f"Pseudomedian {np.median(walsh):.1f} pg/mL")Sorted differences: -30 -25 -20 0 5 10 20 30 40 45 65 65 70 75 80 85 110 125Default, zero dropped: T = 15, p = 0.0036Exact, zero ranked: T = 18, p = 0.0020Normal approximation with correction: T = 15, p = 0.0039Pseudomedian 42.5 pg/mLR 4.6 computes an exact p-value from the permutation distribution of the observed ranks, with the zero ranked and then set aside as Pratt proposed, and it prints no warning: V = 152, p = 0.0020. Earlier R versions could not do that. They dropped the zero, used a normal approximation with a continuity correction, and warned “cannot compute exact p-value with ties” and “cannot compute exact p-value with zeroes”. exact = FALSE gives that older result, V = 138 and p = 0.0039. Those warnings report an approximate p-value and no fault in the data.
SciPy’s default also drops the zero. With ties or zeros and more than 13 differences it uses the normal approximation, without a continuity correction and without a message, and returns p = 0.0036. Adding correction=True returns the 0.0039 of older R. zero_method="pratt" with a PermutationMethod that enumerates all 2^18 sign patterns reproduces the exact result of R, p = 0.0020.
The statistics differ in definition as well. R reports V, the sum of the positive ranks. SciPy reports T, the smaller of the positive and the negative sum. With the zero ranked, V = 152 and T = 18 add up to 170, the total of ranks 2 to 18.
One table therefore gives p = 0.0020, 0.0036, or 0.0039 with three defensible settings. The three agree on the reading here, and near a decision threshold they would not. Report how zeros were handled and whether the p-value is exact.
The estimate that belongs to this test is the pseudomedian, the median of the averages of every pair of differences. It is 42.5 pg/mL in both languages. R adds an exact interval, 20.0 to 67.5 pg/mL, and prints its achieved coverage of 95.6%, because a rank-based interval can only take certain coverage levels. SciPy has no function for that interval, so the Python tab prints the estimate alone. For symmetric differences the pseudomedian and the mean estimate the same center, and here 42.5 sits next to the mean of 41.67.
Report the result
Section titled “Report the result”Give the mean difference in the units of the assay, its interval, the test, and the number of pairs: “The adjuvant raised TNF by 41.7 pg/mL on average (95% CI 18.8 to 64.6 pg/mL; paired t-test, t = 3.84, 17 degrees of freedom, p = 0.0013; 18 donors).” Show the paired lines or the differences in the figure, because two box plots side by side hide the pairing that the analysis used. The DABEST packages on the estimation statistics page draw the estimate and its interval beside the data.
Four mistakes are specific to this design.
- Technical replicates are not pairs. Three wells per culture give one mean per donor and condition, and each donor still contributes one difference.
- Match the two values by
donor_id, never by row position. A table sorted on one column after export breaks every pair, and both tests still run without complaint. - A donor with one missing value has no difference. R drops that pair without a message, and
ttest_rel()returnsnanunless you passnan_policy="omit". Count the complete pairs and report that number. - The adjuvant here adds an amount that does not depend on the baseline. When a treatment multiplies the baseline instead, the raw differences grow with it. Take logs first; the mean difference of the logs is then a log fold change.
With three or more conditions per unit, do not run unadjusted paired tests on every pair of conditions. The repeated measures page tests the conditions together and adjusts the planned comparisons as one family.
Scientific references
Section titled “Scientific references”Student, 1908 derives the distribution of the mean of a small sample relative to the standard deviation estimated from that sample, the basis of the t-test that this page applies to the differences.
Wilcoxon, 1945 introduces the signed-rank test for paired comparisons, along with the rank-sum test for unpaired ones.
Pratt, 1959 examines zeros and ties in the signed-rank procedure and proposes to rank the zeros before dropping them.
Hodges and Lehmann, 1963 derive estimates of location from rank tests, including the pseudomedian reported with the signed-rank test.
Further reading
Section titled “Further reading”The R wilcox.test reference describes the exact conditional test that R applies to tied differences and the confidence interval for the pseudomedian. Compare it with the help page of your own R version when a p-value does not match this page.
The SciPy wilcoxon reference lists the three zero_method options and states when method="auto" switches from an exact p-value to the normal approximation.
The SciPy ttest_rel reference documents the result object, its confidence_interval() method, and the nan_policy argument for incomplete pairs.
The two-group tests page covers Welch’s t-test and the rank-sum test for independent groups, the designs in which no pairing exists.
The estimation statistics page reports effects with bootstrap intervals and estimation plots, an alternative display for the mean difference computed here.