Command reference
egen — calculate row summaries and group statistics
Create a variable with a named summary function. Use egen to average several columns within each observation, repeat a group statistic on its members, or assign identifiers to combinations of values.
Syntax
egen [type] newvar = function(arguments) [if condition] [in first/last] [, options]
newvar must be a new name. Functions such as mean(math) summarize one variable across observations; rowmean(read write math) works across several variables within each observation. The arguments here are variable names. Use generate for ordinary arithmetic expressions.
Functions and their options
Example
The sample combines an overall mean and count, standardized math scores, row means and totals, and IDs for demographic groups. The listing includes a student with a missing writing score so you can compare the row functions.
clear
import delimited "data/student_scores.csv"
egen mean_math = mean(math)
egen count_math = count(math)
egen z_math = std(math)
egen score_mean = rowmean(read write math)
egen score_total = rowtotal(read write math)
egen race_female = group(race female)
list id math mean_math count_math z_math score_mean score_total race_female in 13/16
Sample data included. Opens in a new tab; click Run.
What to look for
mean_math repeats 57.375 and count_math repeats 24. For student 15, reading is 49, math is 50, and writing is missing: score_mean is 49.5 and score_total is 99. The row mean averages two observed subjects. Students with the same race and female values share a race_female ID.