Standardize variables by group

Unfortunately, the otherwise great Stata command egen does not allow to standardize variables group, e.g. for each year separately. There is a small get-around by calculating mean and SD first, and then manually creating the standardized the variable (and then you really wonder why this is not implemented in Stata).

* StandardizeVAR by year
by year: egen VAR_mean= mean(VAR)
by year: egen VAR_sd = sd(VAR)
by year: gen VAR_std = (VAR-VAR_mean)/VAR_sd

or, if you need to do it for several variables at once

* StandardizeVAR1 VAR2 VAR3 by year
foreach var of varlist VAR1 VAR2 VAR3 {

by year: egen `var'_mean= mean(`var')
by year: egen `var'_sd = sd(`var')
by year: gen `var'_std = (`var'-`var'_mean)/`var'_sd

Leave a Reply