Foreach - Loop Over Items: Syntax Description Remarks and Examples Also See
Foreach - Loop Over Items: Syntax Description Remarks and Examples Also See
com
foreach — Loop over items
Syntax
foreach lname in | of listtype list {
Stata commands referring to ‘lname’
}
Allowed are
Description
foreach repeatedly sets local macro lname to each element of the list and executes the commands
enclosed in braces. The loop is executed zero or more times; it is executed zero times if the list is
null or empty. Also see [P] forvalues, which is the fastest way to loop over consecutive values, such
as looping over numbers from 1 to k .
foreach lname in list {. . .} allows a general list. Elements are separated from each other by one
or more blanks.
foreach lname of local list {. . .} and foreach lname of global list {. . .} obtain the list
from the indicated place. This method of using foreach produces the fastest executing code.
1
2 foreach — Loop over items
foreach lname of varlist list {. . .}, foreach lname of newlist list {. . .}, and foreach
lname of numlist list {. . .} are much like foreach lname in list {. . .}, except that the list is given
the appropriate interpretation. For instance,
foreach x in mpg weight-turn {
...
}
has two elements, mpg and weight-turn, so the loop will be executed twice.
foreach x of varlist mpg weight-turn {
...
}
has four elements, mpg, weight, length, and turn, because list was given the interpretation of a
varlist.
foreach lname of varlist list {. . .} gives list the interpretation of a varlist. The list is expanded
according to standard variable abbreviation rules, and the existence of the variables is confirmed.
foreach lname of newlist list {. . .} indicates that the list is to be interpreted as new variable
names; see [U] 11.4.2 Lists of new variables. A check is performed to see that the named variables
could be created, but they are not automatically created.
foreach lname of numlist list {. . .} indicates a number list and allows standard number-list
notation; see [U] 11.1.8 numlist.
Introduction
foreach has many forms, but it is just one command, and what it means is
foreach value of a list of things, set x equal to each and {
execute these instructions once per value
and in the loop we can refer to ‘x’ to refer to the value
}
We use the name x for illustration; you may use whatever name you like. The list itself can come
from a variety of places and can be given a variety of interpretations, but foreach x in is easiest
to understand:
foreach x in a b mpg 2 3 2.2 {
. . . ‘x’ . . .
}
foreach — Loop over items 3
The list is a, b, mpg, 2, 3, and 2.2, and appears right in the command. In some programming
instances, you might know the list ahead of time, but often what you know is that you want to do the
loop for each value of the list contained in a macro, for instance, ‘varlist’. Then you could code
foreach x in ‘varlist’ {
. . . ‘x’ . . .
}
Both work, but the second is quicker to execute. In the first, Stata has to expand the macro and
substitute it into the command line, whereupon foreach must then pull back the elements one at a
time and store them. In the second, all of that is already done, and foreach can just grab the local
macro varlist.
The two forms we have just shown,
foreach x in ... {
. . . ‘x’ . . .
}
and
foreach x of local . . . {
. . . ‘x’ . . .
}
are the two ways foreach is most commonly used. The other forms are for special occasions.
In the event that you have something that you want to be given the interpretation of a varlist,
newvarlist, or numlist before it is interpreted as a list, you can code
foreach x of varlist mpg weight-turn g* {
. . . ‘x’ . . .
}
or
foreach x of newlist id values1-values9 {
. . . ‘x’ . . .
}
or
foreach x of numlist 1/3 5 6/10 {
. . . ‘x’ . . .
}
Just as with foreach x in . . . , you put the list right on the command line, and, if you have the list
in a macro, you can put ‘macroname’ on the command line.
If you have the list in a macro, you have no alternative but to code ‘macroname’; there is no
special foreach x of local macroname variant for varlist, newvarlist, and numlist because, in those
cases, foreach x of local macroname itself is probably sufficient. If you have the list in a macro,
then how did it get there? Well, it probably was something that the user typed and that your program
has already parsed. Then the list has already been expanded, and treating the list as a general list is
adequate; it need not be given the special interpretation again, at least as far as foreach is concerned.
4 foreach — Loop over items
foreach . . . of varlist
foreach lname of varlist varlist allows specifying an existing variable list.
foreach lname of varlist varlist can be useful interactively but is rarely used in programming
contexts. You can code
syntax [varlist] . . .
foreach var of varlist ‘varlist’ {
...
}
but that is not as efficient as coding
6 foreach — Loop over items
syntax [varlist] . . .
foreach var of local varlist {
...
}
because ‘varlist’ has already been expanded by the syntax command according to the macro
rules.
Technical note
syntax [varlist] . . .
foreach var of local varlist {
...
}
is also preferable to
syntax [varlist] . . .
tokenize ‘varlist’
while "‘1’" != "" {
...
macro shift
}
or
syntax [varlist] . . .
tokenize ‘varlist’
local i = 1
while "‘‘i’’" != "" {
...
local i = ‘i’ + 1
}
because it is not only more readable but also faster.
foreach . . . of newlist
newlist signifies to foreach that the list is composed of new variables. foreach verifies that
the list contains valid new variable names, but it does not create the variables. For instance,
. foreach var of newlist z1-z4 {
2. gen ‘var’ = runiform()
3. }
foreach . . . of numlist
foreach lname of numlist numlist provides a method of looping through a list of numbers.
Standard number-list notation is allowed; see [U] 11.1.8 numlist. For instance,
. foreach num of numlist 1/4 8 103 {
2. display ‘num’
3. }
1
2
3
4
8
103
foreach — Loop over items 7
If you wish to loop over many equally spaced values, do not code, for instance,
foreach x in 1/1000 {
...
}
Instead, code
forvalues x = 1/1000 {
...
}
foreach must store the list of elements, whereas forvalues obtains the elements one at a time by
calculation; see [P] forvalues.
Example 4
. foreach x in alpha "one two" three four {
2. display
3. display ‘" x is |‘x’|"’
4. display ‘"ferest() is |‘ferest()’|"’
5. }
x is |alpha|
ferest() is |"one two" three four|
x is |one two|
ferest() is |three four|
x is |three|
ferest() is |four|
x is |four|
ferest() is ||
‘ferest()’ is available only within the body of the loop; outside that, ‘ferest()’ evaluates to
"". Thus you might code
foreach x ... {
...
if . . . {
local lastx ‘"‘x’"’
local rest ‘"‘ferest()’"’
continue, break
}
}
// ‘lastx’ and ‘rest’ are defined
Also see
[P] continue — Break out of loops
[P] forvalues — Loop over consecutive values
[P] if — if programming command
[P] levelsof — Levels of variable
[P] while — Looping
[U] 18 Programming Stata
[U] 18.3 Macros