Looping in Stata

advertisement
Looping in Stata
plus some basic
programming commands
With thanks to Tim Collier and Mona Abdalla
Topics to Cover
•
•
•
•
•
•
Macros
While Loops
Foreach & Forvalues (briefly)
Useful programming commands
Examples
Random useful commands (pt.2)
Macros I
• Local Macros
– Have a name and contents which can contain
anything
– local lname “contents” or local lname=expression
• local one “1”
or
local two=`1’+1
– Local Macro’s called by single quotes: `’
• di `one’
or
di `two’
– Can only be called and altered within a program or do
file (i.e. lost when a do file ends)
Macros II
• Global Macros
– As local except can be called at any time: are
retained with
– Global Macro’s called by dollar sign $
• global one 1
• di $one
• Attributing Commands to Function Keys
• global F5 “cd C:\looping ;”
Macros III
Local Macros can be assigned variables or files
used within a program or do file which are
erased when a do file ends
• Temporary Variables
• tempvar tempvarname tempvarname
• Temporary Files
• tempfile tempfilename
Both are called using single quotes
• `tempvarname’ or `tempfilename’
Looping - while
A very simple command but with wide application. Can
be used to effectively reduce anfractuous repetition in do
files and programs.
while expression {
stata commands
...
}
– while evaluates the expression and if true
executes the commands in brackets. It then repeats
until expression is false
– while may be nested within other while commands
Looping – while
• Examples of expression
•
local i=5
while `i’>0 {
(contents…)
local i=`i’-1
}
•
while `i’!=“” {
(contents…)
macro shift
}
• see do file examples
Foreach & Forvalues
• Both foreach and forvalues are just
specialized while loops
• foreach loops over elements of a local or
global macro or variables in a varlist
• forvalues loops over series or lists of
numbers
(see zoe’s examples and stata help…)
Useful Programming Commands I
• Programs with standard Stata syntax need to start with:
program define progname
syntax varlist(min=#) [if] [in], [options]
tokenize “`varlist’”
• syntax – defines what you want as standard stata
syntax
• tokenize varlist – divides variables following the
command into separate local macros with names `1’, `2’,
`3’…
• preserve – stores the data in a temporary file
• restore – returns the data that existed at the point of
preserving
Useful Programming Commands II
• Posting results to a Stata data file
– need to use three commands:
postfile temp varlist using filename
[commands…]
post (var1content) (var2content) …
postclose temp
– The data file filename.dta will then be
saved containing variables in varlist
Random useful commands (pt.2)
• capture – suppresses all output (useful but
use with caution)
• #delimit – resets the character that marks
the end of a command (only in do and
program files)
Download