-foreach- for all

If you are still doing this:

gen lnX=ln(X)
gen lnY=ln(Y)
gen lnZ=ln(Z)
gen lnX2=lnX^2
gen lnY2=lnY^2
gen lnZ2=lnZ^2

then you are wasting a lot of space (and time). Stata is a programming language. It does not only have the ready-to-use statistical/econometric packages but is also capable of doing a lot of things, and one of them is looping or doing repetitive tasks. For example, the 6 lines above can be written concisely as:

foreach var of varlist X Y Z{
gen ln<em>var</em>’=ln(var’)
gen ln<em>var</em>’<em>2</em>=(lnvar’)^2

[Note: the punctuations that enclose var are not the same. The first (`) is a backquote (the one below the tilde, ~, in the keyboard) and the second (‘) is the apostrophe (the one below the quotation mark “). Thanks to Clarence for pointing this out.]

The loop above repeats the 2 -gen- commands for each of the variables in varlist. The other variants of -foreach- are:
  1. List defined in macros (local or global). For example, we define a local macro called “country” with the list of countries phl, sgp, and tha:

local country phl sgp tha
foreach c of local country{
use data`c’.dta, clear

What if you want a loop across a list of 100 items, is it necessary to list all the items? There are 2 ways to do this. One is to list all the items as the example above, and the other is to use -levelsof- For example,

levelsof varname, local(macroname)
foreach c of local macroname{
display “`c’”

If vaname is countrycode, i.e., the list of country 3-letter codes, the line “levelsof varname, local(macroname)” above is the same as:

local macroname afg bel chn … zam
  1. List of numbers. For example, years:

foreach year of numlist 1970 1980 1990{

or -forvalues- (future post).

The -foreach- command is very handy and is accessible to all. I find Nicolas Cox’s “How to face lists with fortitude” and “How to repeat yourself without going mad” and Christopher Baum’s “A little bit of Stata programming goes a long way…” very instructive.

Leave a Reply