egen
Adds a column holding a group summary — the group's average, total, biggest.
What we have
- group statistics:
count,max,mean,median,min,sd,sum,total - across a row:
rowtotal,rowmean,rowmax,rowmin,rowmiss,rownonmiss group(),tag()andseq()by(), or thebysortprefix
Coming later
pctile(),rank(),cut()and the rest of Stata's egen library
How you write it
egen [type] newvar = function(var) [, by(varlist)]
Square brackets mean optional. A vertical bar means choose one.
What it does
Where generate works across a row, egen works down a column or within a group. egen statemean = mean(mpce), by(state) puts each state's average beside every household in that state, so you can compare a household with its own state rather than with the country.
It knows mean, sum, total, max, min, sd, median and count, plus three helpers: group() turns a combination of columns into a single numbered group, tag() marks one row per group (so you can count groups), and seq() numbers rows.
Try it
Every example below was run after sysuse vira.sample02, clear.
. egen double statemean = mean(mpce), by(state)
The same thing in pandas and in R
pandas
df["statemean"] = df.groupby(['state'])["mpce"].transform("mean")
R
library(dplyr)
df <- df %>% group_by(state) %>% mutate(statemean = mean(mpce,
na.rm = TRUE)) %>% ungroup()
# This R was run in a real R (4.6.1) and gave the same numbers.