ranksum: compare two independent groups
Compare the distributions of two independent groups using ranks, with approximate and exact inference plus an interpretable probability-of-order estimate.
Run a Wilcoxon rank-sum test
The example compares the distribution of math scores between the two values of female in the synthetic teaching dataset.
clear
import delimited "data/student_scores.csv"
ranksum math, by(female) exact porder
by(female) defines two independent groups. exact requests the randomization-distribution p-value, while porder reports an estimate of the probability that a draw from the first group exceeds a draw from the second.
Output from stats.camp
Two-sample Wilcoxon rank-sum (Mann-Whitney) test
female | Obs Rank sum Expected
-------------+---------------------------------
0 | 12 101 150
1 | 12 199 150
-------------+---------------------------------
Combined | 24 300 300
Unadjusted variance 300
Adjustment for ties -0.26087
Adjusted variance 299.73913
Ho: math(female==0) = math(female==1)
z = -2.830
Prob > |z| = 0.0047
P{math(female==0) > math(female==1)} = 0.1597
Exact prob = 0.0034
How to interpret the result
Each value is replaced by its rank in the combined sample. Group 0 has a rank sum of 101 rather than the null expectation of 150, so its observed values tend to be lower in this invented dataset. The normal-approximation two-sided p-value is 0.0047 and the requested exact p-value is 0.0034.
The porder estimate is 0.1597: a randomly selected group-0 value is estimated to exceed a randomly selected group-1 value about 16% of the time. Ties contribute half a comparison and also produce the displayed variance adjustment.
ranksum, ttest, and signrank answer different questions
ranksum, also called the Mann–Whitney test, is for two independent groups and works with the ordering of observations.ttestcompares means under the assumptions of the chosen one-sample, paired, or independent-sample form.signrankis the rank-based command for paired or matched measurements; it is not interchangeable withranksum.- A rank-sum result is not automatically a test of medians. A simple location-shift interpretation requires suitable distributional assumptions.
Common options and checks
by()must identify exactly two nonmissing groups in the analysis sample.ifandinqualifiers restrict the rows before ranks are calculated.exactcan be useful for smaller samples; computation becomes more demanding as sample size grows.pordersupplies an effect-size-style probability, but its direction depends on which group sorts first.- Check independence, ties, group coding, missingness, and the shapes of both distributions before interpretation.
See the current ranksum entry and Stata's ranksum manual for an external reference.
Related guides
Try the Wilcoxon rank-sum test
Clone the example repository in stats.camp and open the exact do-file shown on this page. No stats.camp account is required.
Run the rank-sum example