*Stata programming by Example *Tutorial 3 **Example 1, loops *--------------Start Example 1 ----------------* sysuse auto, clear forvalues i=1/10 { display as text "`i'" } *--------------End Example----------------------* *--------------Start Example 2 ----------------* sysuse auto, clear forvalues i=0 (2) 10 { display as text "`i'" } *--------------End Example----------------------* *--------------Start Example 3 ----------------* sysuse auto, clear forvalues i=2 (2) 10 { list mpg in `i' } *--------------End Example----------------------* * Using the trace command to see what is being substituted *--------------Start Example 4 ----------------* sysuse auto, clear set trace on forvalues i=2 (2) 10 { list mpg in `i' } set trace off *--------------End Example----------------------* help trace *--------------Start Example 5 ----------------* sysuse auto, clear set more off summarize mpg forvalues i=1/`=_N' { list mpg in `i' } *--------------End Example----------------------* * for more details in `=_N' see Stata 10 user guide 18.3.8 *--------------Start Example 6 ----------------* sysuse auto, clear foreach i in 1 2 3 4 { list mpg in `i' } *--------------End Example----------------------* *--------------Start Example 7 ----------------* sysuse auto, clear foreach i of varlist mpg price { histogram `i' sleep 1000 } *--------------End Example----------------------* help sleep *--------------Start Example 8 ----------------* local a 2 foreach i of local a { display "`i'" } *--------------End Example----------------------* *--------------Start Example 9 ----------------* local a " one two three" foreach i of local a { display "`i'" } *--------------End Example----------------------* help foreach *see further examples on the Stata online help page for this command *--------------Start Example 10 ----------------* local i=0 //starting value of i while `i' < 10 { local ++i //increments i by 1 , more on incrementing later display "`i'" } *--------------End Example----------------------* help while *--------------Start Example 11 ----------------* local i=0 //starting value of i while `i' < 10 { local ++i //increments i by 1 , more on incrementing later display "`i'" continue, break } *--------------End Example----------------------* help continue *End tutorial 3 - programming Stata