Stata Looping
Stata offers several structures and commands for looping; select the one most appropriate for what is being looped over.
Contents
Literal List
To iterate over tokens in a literal list, try:
foreach localname in a b c { replace string = subinstr(string, "`a'", "-", .) }
Local Macro List
To iterate over tokens in a local macro, try:
levelsof GROUPVAR, local(groups_of_GROUPVAR) foreach localname of local groups_of_GROUPVAR { generate group = `localname' }
Global Macro List
To iterate over tokens in a global macro, try:
global CLOSED_COHORTS="1 2 3" foreach localname of global COHORTS { assert complete==1 if cohort==`localname' }
Variable List
To iterate over a list of variables, try:
foreach localname of varlist VAR1-VAR9 { assert `localname' != . }
Note that _all can be substituted for * to mean 'all variables.
New Variable List
To iterate over a list of new variables, try:
foreach localname of newlist VAR1-VAR9 { generate `localname' = . }
Number List
to iterate over a number list, try:
foreach localname of numlist 1/9 { count if VAR==`localname' }
Note that the syntax for number lists includes:
a b c (a literal number list)
a,b,c (same as above)
a/b (a range of a to b, which can be ascending or descending)
a to b (same as above)
a(i)b (a range of a to b increasing or decreasing in increments of i, which can be positive or negative, integer or decimal)
a[i]b (same as above)
- and any combination of the above
ForValues
An alternate syntax for iterating over number values is:
forvalues localname = 1/9 { count if VAR==`localname' }
The rules for forvalues number lists are:
a/b (a range of a to b, which can be ascending or descending)
a(i)b (a range of a to b increasing or decreasing in increments of i, which can be positive or negative, integer or decimal)
a b to c (a range of a to c increasing or decreasing in increments of b-a)
a b : c (same as above)