Sie sind auf Seite 1von 1

Programming Building Blocks basic components of programming Loops: Automate Repetitive Tasks

R- AND E-CLASS: Stata stores calculation results in two* main classes:

with Stata 14.1 Cheat Sheet ANATOMY OF A LOOP see also while
For more info see Stata’s reference manual ( r return results from general commands
such as summary or tabulate e return results from estimation
commands such as regress or mean
Stata has three options for repeating commands over lists or values:
foreach, forvalues, and while. Though each has a different first line,
1 Scalars both r- and e-class results contain scalars To assign values to individual variables use: the syntax is consistent:
scalar x1 = 3 Scalars can hold
1 SCALARS r individual numbers or strings objects to repeat over

create a scalar x1 storing the number 3 numeric values or 2 MATRICES e rectangular array of quantities or expressions foreach x of varlist var1 var2 var3 { open brace must
appear on first line
arbitrarily long strings temporary variable used
scalar a1 = “I am a string scalar” e pointers that store text (global or local) only within the loop
create a scalar a1 storing a string * there’s also s- and n-class requires local macro notation

2 Matrices e-class results are stored as matrices 4 Access & Save Stored r- and e-class Objects command `x', option command(s) you want to repeat
can be one line or many
matrix a = (4\ 5\ 6) matrix b = (7, 8, 9) Many Stata commands store results in types of lists. To access these, use return or
close brace must appear
create a 3 x 1 matrix create a 1 x 3 matrix ereturn commands. Stored results can be scalars, macros, matrices or functions. } on final line by itself
summarize price, detail mean price
matrix d = b' transpose matrix b; store in d r return list e ereturn list FOREACH: REPEAT COMMANDS OVER STRINGS, LISTS, OR VARIABLES
returns a list of scalars returns list of scalars, macros,
matrix ad1 = a \ d matrix ad2 = a , d matrices and functions foreach x in|of [ local, global, varlist, newlist, numlist ] {
row bind matrices column bind matrices scalars:
r(N) = 74 Results are replaced
e(df_r) = 73 Stata commands referring to `x' list types: objects over which the
commands will be repeated
matselrc b x, c(1 3) findit matselrc r(mean) = 6165.25... each time an r-class e(N_over) = 1 }
loops repeat the same command
select columns 1 & 3 of matrix b & store in new matrix x r(Var)
/ e-class command
is called
1 STRINGS over different arguments:
mat2txt, matrix(ad1) saving(textfile.txt) replace ... e(rank) = 1 foreach x in auto.dta auto2.dta { same as...
sysuse "auto.dta", clear
export a matrix to a text file sysuse "`x'", clear tab rep78, missing
ssc install mat2txt generate p_mean = r(mean) generate meanN = e(N) tab rep78, missing sysuse "auto2.dta", clear
DISPLAYING & DELETING BUILDING BLOCKS create a new variable equal to create a new variable equal to } tab rep78, missing
average of price obs. in estimation command LISTS
[scalar | matrix | macro | estimates] [list | drop] b foreach x in "Dr. Nick" "Dr. Hibbert" { display length("Dr. Nick")
list contents of object b or drop (delete) object b preserve create a temporary copy of active dataframe display length ( "` x '" ) display length("Dr. Hibbert")
restore restore temporary copy to original point set restore points to test }
[scalar | matrix | macro | estimates] dir code that changes data
When calling a command that takes a string,
list all defined objects for that class
surround the macro name with quotes.
matrix list b matrix dir scalar drop x1
After you run any estimation command, the results of the estimates are foreach x in mpg weight {
list contents of matrix b list all matrices delete scalar x1 stored in a structure that you can save, view, compare, and export summarize `x'
• foreach in takes any list
as an argument with
regress price weight }
3 Macros public or private variables storing text
estimates store est1
Use estimates store must define list type
elements separated by
summarize mpg
summarize weight
to compile results foreach x of varlist mpg weight { • foreach of requires you
GLOBALS available through Stata sessions PUBLIC store previous estimation results est1 in memory for later use summarize `x' to state the list type,
which makes it faster
eststo est2: regress price weight mpg }
global pathdata "C:/Users/SantasLittleHelper/Stata" ssc install estout
define a global variable called pathdata eststo est3: regress price weight mpg foreign FORVALUES: REPEAT COMMANDS OVER LISTS OF NUMBERS
cd $pathdata add a $ before calling a global macro estimate two regression models and store estimation results iterator Use display command to
change working directory by calling global macro estimates table est1 est2 est3 forvalues i = 10(10)50 { show the iterator value at display 10
global myGlobal price mpg length print a table of the two estimation results est1 and est2 display `i' numeric values over each step in the loop display 20
} which loop will run ...
summarize $myGlobal ITERATORS
summarize price mpg length using global EXPORTING RESULTS i = 10/50 10, 11, 12, ...
The estout and outreg2 packages provide numerous, flexible options for making tables i = 10(10)50 10, 20, 30, ...
LOCALS available only in programs, loops, or .do files PRIVATE after estimation commands. See also putexcel command. DEBUGGING CODE i = 10 20 to 50 10, 20, 30, ...
local myLocal price mpg length esttab est1 est2, se star(* 0.10 ** 0.05 *** 0.01) label set trace on (off ) see also capture and scalar _rc
create local variable called myLocal with the create summary table with standard errors and labels trace the execution of programs for error checking
strings price mpg and length esttab using “auto_reg.txt”, replace plain se
summarize ` myLocal ' add a ` before and a ' after local macro name to call export summary table to a text file, include standard errors PUTTING IT ALL TOGETHER sysuse auto, clear
summarize contents of local myLocal generate car_make = word(make, 1) pull out the first word
levelsof rep78, local(levels) outreg2 [est1 est2] using “auto_reg2.txt”, see replace from the make variable

create a sorted list of distinct values of rep78, export summary table to a text file using outreg2 syntax define the levelsof car_make, local(cmake) calculate unique groups of
car_make and store in local cmake
store results in a local macro called levels local i to be local i = 1
local varLab: variable label foreign can also do with value labels Additional Programming Resources an iterator
local cmake_len : word count `cmake' store the length of local
cmake in local cmake_len
store the variable label for foreign in the local varLab foreach x of local cmake {
download all examples from this cheat sheet in a .do file display in yellow "Make group `i' is `x'"
TEMPVARS & TEMPFILES special locals for loops/programs adoupdate adolist ssc install adolist
tempvar temp1 if `i' == `cmake_len' {
initialize a new temporary variable called temp1
Update user-written .ado files List/copy user-written .ado files
generate `temp1' = mpg^2 save squared mpg values in temp1
tests the position of the
display "The total number of groups is `i'"
 net install package, from ( in brackets when the
iterator, executes contents
summarize `temp1' summarize the temporary variable temp1 install a package from a Github repository condition is true
tempfile myAuto create a temporary file to see also local i = `++i' increment iterator by one
save `myAuto' be used within a program tempname configure Sublime text for Stata 11-14 }

Tim Essam ( • Laura Hughes ( inspired by RStudio’s awesome Cheat Sheets ( updated June 2016
follow us @StataRGIS and @flaneuseks Disclaimer: we are not affiliated with Stata. But we like it. CC BY 4.0