Command reference
collapse — replace observations with grouped summaries
Create a dataset of summary statistics, with one row for the whole sample or one row per group. The result replaces the observation-level dataset in memory.
Syntax
collapse (statistic) [newvar=]sourcevar ... [if condition] [in range] [, by(groupvars)]
A statistic in parentheses applies to the variables following it until another statistic is named. Without a statistic, the default is mean. Use newvar=sourcevar to name an output separately from its source, especially when calculating several statistics from the same variable. if and in select the observations to aggregate.
Statistics and grouping
Example
The example turns 24 synthetic student records into four rows, one for each race code. It calculates mean math and reading scores, the total math score, and the number of available writing scores.
clear
import delimited "data/student_scores.csv"
collapse (mean) mean_math=math mean_read=read (sum) total_math=math (count) n_write=write, by(race)
list
Sample data included. Opens in a new tab; click Run.
What to look for
Each output row now represents a group rather than a student. For race code 1, six math scores total 303 and average 50.50. Race code 3 has n_write=5 because one writing score is missing; it still contains six original records.
| race | mean_math | mean_read | total_math | n_write |
|---|---|---|---|---|
| 1 | 50.50 | 52.17 | 303 | 6 |
| 2 | 60.50 | 58.17 | 363 | 6 |
| 3 | 54.33 | 53.00 | 326 | 5 |
| 4 | 64.17 | 61.33 | 385 | 6 |