Command reference

ranksum — compare two groups using ranks

Run the Wilcoxon rank-sum test, also called the Mann–Whitney test, for two independent groups. It compares the ordering of their observations instead of relying on a difference in arithmetic means.

Syntax

ranksum outcome [if condition] [in first/last], by(group) [exact | noexact] [porder]

Supply one numeric outcome and a group variable with exactly two nonmissing values. The group variable may be numeric or string. The command pools the observations, assigns ranks to the outcome values, and compares each group's rank sum with its null expectation.

if filters observations by a condition, and in selects positions in the current row order. Observations missing either the outcome or group are excluded before ranking. Tied outcome values receive average ranks. Weights are not accepted.

Options

by(group)
Required: identifies the two independent groups. The displayed first group determines the direction of the z statistic and the probability reported by porder.
exact
Request p-values from the exact rank-sum randomization distribution. Exact calculation is already attempted by default for a combined sample of at most 200 observations; this option requests it for larger samples too. The explicit request is limited to 1,000 observations and may be infeasible for some rank patterns.
noexact
Skip exact calculation and report the normal approximation. Use this when an exact calculation is unnecessary or too costly. Do not combine it with exact.
porder
Report the proportion of cross-group comparisons in which a value from the first group exceeds one from the second, counting each tie as half. Values below 0.5 indicate that the first group's observations tend to be lower.

Example

Compare the math-score distributions of the two female groups in the bundled synthetic student data. Request both an exact p-value and porder to see the test result alongside the direction and size of the ordering difference.

clear
import delimited "data/student_scores.csv"
ranksum math, by(female) exact porder
Open example in browser

Sample data included. Opens in a new tab; click Run.

What to look for

Group 0 has a rank sum of 101, below the null expectation of 150, so its math scores tend to be lower in this synthetic sample. The normal-approximation z statistic is about −2.830, with a two-sided p-value of 0.0047; the exact p-value is about 0.0034.

The porder estimate is about 0.1597. Interpreted as pairwise comparisons, group-0 values exceed group-1 values about 16% of the time, with ties counted as half. This describes ordering in the example, not a causal effect of group membership.

Example result
GroupObservationsRank sumExpected rank sum
012101150
112199150