Stata Looping

Stata offers several structures and commands for looping; select the one most appropriate for what is being looped over.


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:


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:


CategoryRicottone

Stata/Looping (last edited 2023-06-10 13:26:47 by DominicRicottone)