Book Image

Data Analysis with STATA

Book Image

Data Analysis with STATA

Overview of this book

Table of Contents (16 chapters)
Data Analysis with Stata
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Loops in Stata


Loops is a very important concept in Stata. For various calculations and executions, putting code into loops is an extremely useful concept. The command used to create loops in Stata is foreach. The syntax for such a command is as follows:

foreach macro_name in list_name {
command(s)
}

Now, let's take a small example:

Foreach ball_size in ten twenty thirty [
display " 'ball_size' "
]

In this code, ball_size acts as the name of the written macro. It has a list of the elements that need to be part of the macro. Stata's macro processor breaks this list into appropriate sections. In this case, the sections of the current code can be as per the element list, such as ten, twenty, and thirty.

The brackets denote the beginning and the ending of the loop:

  • [: This denotes the beginning of the loop

  • ]: This denotes the end of the loop

The Stata macro processor analyzes the entire list, which is your input in the macro statement. It also identifies all the elements in the list. For the first...