If you are still doing this:

**gen **ln

*X*=ln(

*X*)

**gen **ln

*Y*=ln(

*Y*)

**gen **ln

*Z*=ln(

*Z*)

**gen **ln

*X2*=ln

*X*^

*2*
**gen **ln

*Y2*=ln

*Y*^

*2*
**gen **ln

*Z2*=ln

*Z*^

*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>=(ln`

*var*’)^

*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:

- 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*
- 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.

Filed under: Basic Programming | Tagged: foreach | Leave a comment »