sysuse lifeexp, clearkeep ifinlist(country, "Italy", "France", "Germany")
** Understanding what Stata does during a loopset trace onset tracedepth 1// specify how much detail Stata will showset trace off
set trace onforeach c in Italy France Germany {
// c is a local containing Italy in first iteration, France in second iteration and so on. display"`c'"
}
set trace off
/* Hint: The above example has one major disadvantage: You need to look up the country names and then insert them in the loop header. The command levelsof makes life easier. */levelsof country, local(country_names)
// All distinct values of the variable country (i.e. the country names) are stored in the local country_name.display`"`country_names'"'// Note that the order is automatically alphabetical. Remember to use compound quotes // when displaying the content as the local contains double quotes.foreach c in`country_names' {
//First the local is replaced by its content and then the loop is performed like in the example above. display"`c'" sum gnppc lexp if country == "`c'"// The content of c is inserted in two places: After the display command to make the output // easier to read and the condition after country ==
}
Loops over structured lists
* Foreach: loop over structured list: varlistsysuse census, clear// We load the census dataset which contains different population-related variables for a range of US-American States.// As we are using a structured varlist we can use pop* as a shortcut for all variables starting with pop.foreach v of varlist pop* {
sum`v'
}
* Foreach: loop over structured list: newlistclearset obs 30foreach var of newlist z1-z20 {
// The loop first checks whether z1, z2, z3, etc. already exist and then // inserts them into the local var in the order they are specified. gen`var' = runiform()
// generates new variables containing random numbers from a uniform distribution between 0 and 1
}
* Foreach: loop over structured list: numlistforeach num of numlist14/813(2)21103 {
// We use a range of shortcuts in the list of numbers (4/8=4,5,6,7,8; 13(2)21=13,15,17,19,21) display`num'
}