Mann-Whitney U Test
The engine for Robust Comparative Discovery. This model audits the stochastic dominance between two independent groups, revealing if one group typically scores higher than the other without assuming normality.
What is it?
Mann-Whitney U Test (Wilcoxon Rank-Sum) compares ranked scores of two independent groups. Nonparametric alternative to Independent samples T-Test.
When to use it
- Two Groups: Independent treatments or categories.
- Non-Normal Data: Continuous outcomes violating normality or ordinal metrics.
Core Idea
Combines and ranks all measurements. If a significant separation exists, one group will cluster at the lower ranks and the other at the higher ranks:
Hypotheses
How it works
- Combine all scores and sort them to assign overall ranks.
- Sum the ranks for Group 1 (R1) and Group 2 (R2).
- Compute U stats. Set U = min(U1, U2).
- Assess significance (normal approximation used for N > 10).
Assumptions
Effect Size
Rank-Biserial correlation: **r = 1 - (2U / (N1 * N2))**. Yields value from -1.0 to +1.0 indicating degree of stochastic separation.
Quick Example
| Group | Rank Sum | U Stat |
|---|---|---|
| G1 (N=10) | 75 | U = 20 (p = 0.012) |
| G2 (N=10) | 135 |
Mann-Whitney Ranks Live Laboratory
Adjust the Group 2 shift to see how overall ranks sort and change rank sum indicators.
| Metric | Group 1 | Group 2 |
|---|---|---|
| Sample Size | 12 | 12 |
| Rank Sum | 133 | 167 |
| U statistic | 55 | |
| p-value | 0.3314 | |
Hypotheses
Pragmatic null and alternative hypotheses defined in mathematical notation.
H₀: The two distributions are identical (P(X > Y) = 0.5)
Hₐ: One distribution is stochastically larger than the other (P(X > Y) ≠ 0.5)
Tests stochastic dominance via rank sums. IMPORTANT: Only interpretable as a test of medians when distributions have similar shapes (same variance and skewness). Otherwise, it tests whether one distribution tends to have larger values than the other (stochastic dominance), not specifically medians.
Assumptions
The core mathematical criteria needed to ensure that statistical testing remains unbiased and valid.
Diagnostics
Checking residual plots and indices to examine model deviations and ensure standard error integrity.
- Side-by-side boxplots for each group to compare distributions
- Overlaid density plots or histograms to assess shape similarity
- Descriptive statistics per group (median, IQR, range, n)
- Check proportion of ties in rankings
- Q-Q plots per group (to verify non-normality justifies nonparametric approach)
- Cumulative distribution function (CDF) plots for both groups
- Shapiro-Wilk test per group (if considering parametric alternative)
- Variance ratio and IQR ratio between groups
- Scatterplot of ranks to visualize stochastic dominance
Applied Minds
Review concrete study examples, data layout guidelines, and copy executable syntax scripts.
Pain Reduction Comparison (Classic Mann-Whitney with Ordinal Data)
Research question: Does a new mindfulness-based intervention reduce chronic pain more than standard treatment? Design: RCT with 2 groups (Mindfulness n=40, Standard Treatment n=40). Outcome: Pain reduction on 11-point Numerical Rating Scale (NRS) from baseline to 8 weeks (ordinal, 0-10, higher = more reduction). Data are ordinal and right-skewed. Parametric t-test assumptions violated (Shapiro-Wilk p=.003).
# Mann-Whitney U Test: Mindfulness vs. Standard Treatment for Pain Reduction
# Based on realistic effect sizes from mindfulness-pain meta-analyses
library(tidyverse)
library(effectsize) # For rank biserial correlation
library(coin) # For exact and asymptotic tests
library(rstatix) # For comprehensive nonparametric output
# Simulate realistic ordinal data with right skew (or load: data <- read.csv("pain.csv"))
set.seed(2025)
data <- data.frame(
group = rep(c("Mindfulness", "Standard"), each=40),
pain_reduction = c(
# Mindfulness: median=4, right-skewed ordinal (0-10)
sample(0:10, 40, replace=TRUE, prob=c(0.02, 0.03, 0.04, 0.06, 0.12, 0.15, 0.18, 0.16, 0.12, 0.08, 0.04)),
# Standard: median=2, right-skewed ordinal
sample(0:10, 40, replace=TRUE, prob=c(0.05, 0.10, 0.15, 0.20, 0.18, 0.12, 0.08, 0.06, 0.03, 0.02, 0.01))
)
)
# === STEP 1: Check if Parametric Test is Appropriate ===
# Test normality (if violated, justifies nonparametric approach)
print("=== Normality Tests(to justify Mann-Whitney) ===")
by(data$pain_reduction, data$group, shapiro.test)
# Result: Both groups p < .05 → non-normal, Mann-Whitney appropriate
# Q-Q plots show departure from normality
par(mfrow=c(1,2))
for (grp in c("Mindfulness", "Standard")) {
qqnorm(data$pain_reduction[data$group == grp], main=paste(grp, "Q-Q Plot"))
qqline(data$pain_reduction[data$group == grp])
}
# === STEP 2: Check Mann-Whitney Assumptions ===
# 1. Independence: Confirmed by study design (between-subjects RCT, no repeated measures)
cat("\n=== Assumption Checks ===")
cat("\nIndependence: Confirmed(between-subjects design, no pairing)")
# 2. Similar distribution shapes (for median interpretation)
cat("\n\nShape Similarity:")
# Visual check: boxplots
ggplot(data, aes(x=group, y=pain_reduction, fill=group)) +
geom_boxplot(alpha=0.6) +
geom_jitter(width=0.1, alpha=0.3) +
labs(title="Pain Reduction: Mindfulness vs. Standard Treatment",
subtitle="Ordinal data(NRS 0-10), both right-skewed",
y="Pain Reduction(NRS points)", x="Group") +
scale_fill_brewer(palette="Set2") +
theme_classic() +
theme(legend.position="none")
# Density plots overlaid
ggplot(data, aes(x=pain_reduction, fill=group)) +
geom_density(alpha=0.5) +
labs(title="Distribution Shape Comparison",
subtitle="Similar right-skewed shapes → median interpretation valid",
x="Pain Reduction(NRS)", y="Density") +
scale_fill_brewer(palette="Set2") +
theme_classic()
# Compare IQRs (should be similar for median interpretation)
mindfulness_data <- data$pain_reduction[data$group == "Mindfulness"]
standard_data <- data$pain_reduction[data$group == "Standard"]
iqr_mindfulness <- IQR(mindfulness_data)
iqr_standard <- IQR(standard_data)
iqr_ratio <- iqr_mindfulness / iqr_standard
cat(sprintf("\nMindfulness IQR: %.2f, Standard IQR: %.2f, Ratio: %.2f",
iqr_mindfulness, iqr_standard, iqr_ratio))
if (iqr_ratio >= 0.5 & iqr_ratio <= 2.0) {
cat(" ✓ Similar spreads(ratio 0.5-2.0)")
} else {
cat(" ⚠ Different spreads - interpret as stochastic dominance, not median test")
}
# === STEP 3: Descriptive Statistics ===
cat("\n\n=== Descriptive Statistics ===")
data %>%
group_by(group) %>%
summarise(
n = n(),
Median = median(pain_reduction),
IQR = IQR(pain_reduction),
Mean = mean(pain_reduction),
SD = sd(pain_reduction),
Min = min(pain_reduction),
Max = max(pain_reduction)
) %>%
print()
# === STEP 4: Run Mann-Whitney U Test ===
cat("\n=== Mann-Whitney U Test Results ===")
# Method 1: Base R (Wilcoxon rank sum)
wilcox_result <- wilcox.test(pain_reduction ~ group, data=data,
exact=FALSE, # Use normal approximation (n>20)
correct=TRUE) # Continuity correction
print(wilcox_result)
# Method 2: Using rstatix (comprehensive output)
mw_test <- data %>% wilcox_test(pain_reduction ~ group)
print(mw_test)
# Method 3: Using coin package (exact test if needed)
# For exact test (small samples or many ties):
# exact_test <- wilcox_exact(pain_reduction ~ factor(group), data=data)
# === STEP 5: Effect Size ===
cat("\n=== Effect Size: Rank Biserial Correlation ===")
# Rank biserial correlation (r_rb): standardized U statistic
# Interpretation: small=0.1, medium=0.3, large=0.5 (similar to Cohen's d thresholds)
rbc <- rank_biserial(pain_reduction ~ group, data=data)
print(rbc)
cat(sprintf("\nr_rb = %.3f [95%% CI: %.3f, %.3f]",
rbc$r_rank_biserial, rbc$CI_low, rbc$CI_high))
# Common Language Effect Size: P(Mindfulness > Standard)
cles_value <- cles(pain_reduction ~ group, data=data)
print(cles_value)
cat(sprintf("\nCommon Language Effect Size(CLES): %.1f%%", cles_value$CLES * 100))
cat("\n(Probability that random Mindfulness patient has more pain reduction than random Standard patient)")
# === STEP 6: Visualization with Statistical Annotation ===
# Boxplot with statistical test
ggplot(data, aes(x=group, y=pain_reduction, fill=group)) +
geom_boxplot(alpha=0.6, outlier.shape=NA) +
geom_jitter(width=0.15, alpha=0.3, size=2) +
stat_summary(fun=median, geom="point", size=4, color="red", shape=18) +
labs(title="Pain Reduction: Mindfulness vs. Standard Treatment",
subtitle=paste0("Mann-Whitney U: p=", format.pval(wilcox_result$p.value, digits=3),
", r_rb=", round(rbc$r_rank_biserial, 2)),
y="Pain Reduction(NRS 0-10)", x="Treatment Group") +
scale_fill_brewer(palette="Set2") +
theme_classic() +
theme(legend.position="none") +
annotate("text", x=1.5, y=10,
label=paste0("Median Mindfulness: ", median(mindfulness_data),
"\nMedian Standard: ", median(standard_data)),
size=3.5)
# Cumulative distribution functions
ggplot(data, aes(x=pain_reduction, color=group)) +
stat_ecdf(geom="step", size=1.2) +
labs(title="Cumulative Distribution Functions",
subtitle="Mindfulness curve shifted right → stochastic dominance",
x="Pain Reduction(NRS)", y="Cumulative Probability",
color="Group") +
scale_color_brewer(palette="Set1") +
theme_classic()
# === STEP 7: APA-Style Reporting ===
cat("\n\n=== APA-Style Report ===")
cat(sprintf("
A Mann-Whitney U test was conducted to compare pain reduction between mindfulness-based
intervention and standard treatment in adults with chronic pain. The Mann-Whitney test was
chosen because data were ordinal(11-point NRS) and violated normality assumptions
(Shapiro-Wilk p < .05 in both groups). Distribution shapes were similar(both right-skewed),
allowing interpretation as a median test.
The mindfulness group(Mdn = %.0f, IQR = %.0f) showed significantly greater pain reduction
than the standard treatment group(Mdn = %.0f, IQR = %.0f), U = %.0f, p = %s,
r_rb = %.2f (medium effect). The common language effect size indicated that %.0f%% of the
time, a randomly selected participant from the mindfulness group would have greater pain
reduction than a randomly selected participant from the standard treatment group.
These findings support mindfulness-based interventions as more effective than standard
treatment for chronic pain reduction, consistent with meta-analytic evidence(Bawa et al., 2015).",
median(mindfulness_data), IQR(mindfulness_data),
median(standard_data), IQR(standard_data),
as.numeric(wilcox_result$statistic),
format.pval(wilcox_result$p.value, digits=3, eps=0.001),
rbc$r_rank_biserial,
round(cles_value$CLES * 100, 0)))
# === Optional: Compare to Parametric T-test (if it were appropriate) ===
cat("\n\n=== Comparison: What if we(incorrectly) used t-test? ===")
t_result <- t.test(pain_reduction ~ group, data=data)
cat(sprintf("\nIndependent t-test(INAPPROPRIATE): t=%.2f, p=%s",
t_result$statistic, format.pval(t_result$p.value, digits=3)))
cat(sprintf("\nMann-Whitney U test(APPROPRIATE): U=%.0f, p=%s",
as.numeric(wilcox_result$statistic), format.pval(wilcox_result$p.value, digits=3)))
cat("\nConclusion: Results similar, but Mann-Whitney is the correct choice given ordinal data.")U = 1105, p = .002, r_rb = 0.38 (medium effect). Mindfulness group (Mdn=4, IQR=3) showed significantly greater pain reduction than standard treatment (Mdn=2, IQR=2). Common language effect size: 69% probability that a random mindfulness participant has more pain reduction than a random standard treatment participant. Distribution shapes were similar (both right-skewed), validating median interpretation. Findings support mindfulness interventions for chronic pain, consistent with Bawa et al. (2015) meta-analysis (d=0.32).
Alternatives
Structured fallback pathways for choosing alternative tests when normality or slopes requirements fail.
- Independent T-Test — Reclaim 5% statistical power by returning to the mean-based strike.
- Chi-Square Independence — If most data points are identical, treat the scale as purely nominal.
- Exact Mann-Whitney Strike — Use permutation-based p-values to bypass the tie-correction approximation.
- Brunner-Munzel Test — The robust alternative for stochastic equality when group variances/shapes differ wildly.
Post-hoc
Group mean comparisons and correction controls (e.g. Tukey HSD, Bonferroni) to protect against Family-Wise Error Rates.
Post-hoc pairwise tests defined for this model.
A nonparametric p-value is a starting point. CLES is the elite metric that translates ranks into a language of probability that clinical practitioners can act upon.
Effect Size
Understanding effect sizes (e.g., Cohen's d, Partial Eta-Squared) and clinical impact benchmarks.
Standardized U statistic. Range: -1 to +1. Small: |0.1|, Medium: |0.3|, Large: |0.5| (Cohen's guidelines). Formula: r_rb = 1 - (2U)/(n₁×n₂). Equivalent to difference in proportion of concordant vs. discordant pairs.
Probability that random observation from group 1 exceeds random observation from group 2. Range: 0 to 1. CLES = U/(n₁×n₂). CLES=0.5 means no difference; CLES=0.7 means 70% probability of superiority. Highly interpretable for non-statisticians.
Same as CLES. P(X > Y) where X is from group 1, Y is from group 2. Direct interpretation in applied contexts (e.g., 'Patient on Drug A has 65% probability of better outcome than patient on Drug B').
0.2
0.5
0.8
Sample Size
Guidelines for minimum sample requirements and power analysis parameters.
The 'Rank-Stability' Mandate: A minimum of 20 participants per group is required to ensure that the stochastic dominance audit doesn't collapse due to excessive tied ranks.
| Effect Size | Parameters | Required n |
|---|---|---|
| Small Effect | d=0.20 (Small) | n ≈ 860 total |
| Medium Effect | d=0.50 (Medium) | n ≈ 140 total |
| Large Effect | d=0.80 (Large) | n ≈ 60 total |
The 'Tie Penalty': If your data is highly discrete (e.g., 1-5 Likert scale), the frequency of identical ranks (Ties) will explode, effectively 'Blunting' the U-statistic. Increase sample size by 15% to compensate for rank-precision loss.
Reporting
How to compile statistical results into publication prose matching APA and journal style guides.
A Mann-Whitney U test was conducted to compare DV between group 1 and group 2. State reason for choosing Mann-Whitney: 'Data were ordinal' or 'Data were continuous but violated normality assumptions (Shapiro-Wilk p < .05)' or 'Data showed severe skewness and outliers'. If shapes similar: Distribution shapes were similar between groups (IQR ratio = X.XX), permitting interpretation as a median test. If shapes differ: Distribution shapes differed between groups (IQR ratio = X.XX; group 1 more skewed/variable), so results reflect stochastic dominance rather than pure median difference. Results: Group 1 (Mdn = X.XX, IQR = X.XX) showed significantly higher/lower/did not differ significantly from Group 2 (Mdn = X.XX, IQR = X.XX), U = XXX, p = .XXX, r_rb = .XX interpret: small/medium/large effect. If significant: The common language effect size indicated that XX% of the time, a randomly selected observation from group 1 would be higher/lower than a randomly selected observation from group 2. Conclude with interpretation in research context.
- U-statistic
- p-value
- effect size (rank biserial correlation)
- descriptive statistics per group (median, IQR, n)
- statement about distribution shape similarity
- statement justifying nonparametric approach
- common language effect size (optional but recommended)
Manuscript Lab
Copy standard summary tables and forensic reporting grids to outline analysis details.
| Group | Median | Mean Rank | Sum of Ranks | U | z | p | r (Effect Size) |
|---|---|---|---|---|---|---|---|
| Active | 45.0 | 48.2 | 1928 | 452.5 | -3.12 | .002 | .35 |
| Control | 32.0 | 32.8 | 1312 | — | — | — | — |
The Rank Overlap. Quantifies how many times a score from the Active group ranks higher than a score from Control.
Rank-Biserial Correlation. .35 is a 'Medium' effect size. Indicates a 35% shift in rank probability between groups.
Command Center
Syntax libraries and function parameters for executing calculations in stats packages.
# 1. Execute Mann-Whitney U Test
wilcox.test(score ~ group, data = df, exact = FALSE)
# 2. Extract Effect Size (r)
rstatix::wilcox_effsize(score ~ group, data = df)Mann-Whitney does not test medians unless distributions have the same shape. It actually tests 'Stochastic Dominance'—the probability that Group A ranks higher than Group B.
# Execute Exact Test (Best for small samples or many ties)
coin::wilcox_test(score ~ factor(group), data = df, distribution = 'exact')Common Mistakes
Analytical caveats and corrections to maintain modeling integrity.
References
Scholarly lineage and citation keys grounding the statistical framework.