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

by(groupvars)
Create one output row for each distinct combination of grouping values, retaining those grouping variables. Results are sorted by the grouping variables. Without by(), the selected observations become a single summary row.
(mean), (sum), (count)
Calculate an arithmetic mean, a total, or a count of nonmissing source values. An all-missing numeric group has a sum of 0. Count a variable that is always present when you need the number of observations in each group.
(min), (max), (sd)
Calculate the minimum, maximum, or sample standard deviation of a numeric variable. The standard deviation needs at least two nonmissing values.
(median), (p1) through (p99), (iqr)
Calculate the median, an integer percentile from 1 through 99, or the interquartile range. The interquartile range is the 75th percentile minus the 25th percentile.
(semean) or (sem)
Calculate the standard error of the mean as the sample standard deviation divided by the square root of the nonmissing count.
(first), (last)
Keep the first or last value in the group's current observation order, including a missing value in that position. These statistics accept numeric and string variables.
(firstnm), (lastnm)
Keep the first or last nonmissing value in the group's current observation order. These forms also accept strings, treating empty strings as missing.

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
Open example in browser

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.

Example result
racemean_mathmean_readtotal_mathn_write
150.5052.173036
260.5058.173636
354.3353.003265
464.1761.333856