collapse: grouped means and counts
Replace observation-level data with one row per group and clearly name the summary variables the command creates.
Independent software. Not affiliated with, sponsored by, or endorsed by StataCorp LLC.
Complete example
The source data have 24 synthetic student records in four race groups. One write value is missing, which makes the behavior of (count) visible.
clear
import delimited "data/student_scores.csv"
collapse (mean) mean_math=math mean_read=read (count) n_write=write, by(race)
list
The names before the equals signs are the variables created in the collapsed dataset. by(race) requests one output row for each observed race value.
Output from stats.camp
+-----------------------------------------------+ | # race mean_math mean_read n_write | |-----------------------------------------------| | 1 1 50.50 52.17 6 | | 2 2 60.50 58.17 6 | | 3 3 54.33 53 5 | | 4 4 64.17 61.33 6 | +-----------------------------------------------+
How to read the result
Each row now represents a group rather than a student. For group 1, the mean math score is 50.50 and the mean reading score is 52.17. Group 3 has n_write=5 because count counts nonmissing values of write, not all rows in the group.
If you need a group size regardless of missingness in a particular measure, count a variable known to be present on every relevant row.
Checks, variants, and limits
collapsereplaces the data in memory. Save the source or use a supported preservation workflow before collapsing if you need the individual records again.- Name output variables explicitly when calculating several statistics so downstream commands remain readable.
- After collapsing, verify the number of groups and compare selected results with pre-collapse summaries.
- Do not assume every official statistic, weighting rule, or option combination is implemented.
See the current collapse entry and Stata's collapse manual for an external reference.
Related guides
Run this exact example
Clone the example repository in stats.camp and open the exact do-file shown on this page. No stats.camp account is required.
Open this example