collapse: grouped means and counts

Replace observation-level data with one row per group and clearly name the summary variables the command creates.

Tested 2026-08-06 with the current stats.camp development build · View the do-file on GitHub

Open this example View supported commands

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

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