Looping in Stata

May 10, 2019

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:

Summarizing generated variable


Profile picture

Written by Johan Osterberg who lives and works in Gothenburg, Sweden as a developer specialized in e-commerce. Connect with me on Linkedin

2024 © Johan Osterberg