Looping in Stata is mainly achieved by use of the foreach command. Using the nlsw88 dataset we’ll generate a new variable with observations containing the square root of each observation in the variable wage:
sysuse nlsw88, clear
foreach i in wage {
gen gen`i' = sqrt(`i')
}
su genwage
The foreach loop is pretty straight forward - we generate a variable with the prefix gen followed by name of variable containing the square root of each observation in the variable wage. Then we summarize the new variable: