SlideShare una empresa de Scribd logo
1 de 1
Descargar para leer sin conexión
Programming
Cheat Sheetwith Stata 14.1
For more info see Stata’s reference manual (stata.com)
Tim Essam (tessam@usaid.gov) • Laura Hughes (lhughes@usaid.gov)
follow us @StataRGIS and @flaneuseks
inspired by RStudio’s awesome Cheat Sheets (rstudio.com/resources/cheatsheets) updated June 2016
CC BY 4.0
geocenter.github.io/StataTraining
Disclaimer: we are not affiliated with Stata. But we like it.
PUTTING IT ALL TOGETHER sysuse auto, clear
generate car_make = word(make, 1)
levelsof car_make, local(cmake)
local i = 1
local cmake_len : word count `cmake'
foreach x of local cmake {
display in yellow "Make group `i' is `x'"
if `i' == `cmake_len' {
display "The total number of groups is `i'"
}
local i = `++i'
}
define the
local i to be
an iterator
tests the position of the
iterator, executes contents
in brackets when the
condition is true
increment iterator by one
store the length of local
cmake in local cmake_len
calculate unique groups of
car_make and store in local cmake
pull out the first word
from the make variable
see also capture and scalar _rc
Stata has three options for repeating commands over lists or values:
foreach, forvalues, and while. Though each has a different first line,
the syntax is consistent:
Loops: Automate Repetitive Tasks
ANATOMY OF A LOOP see also while
i = 10(10)50 10, 20, 30, ...
i = 10 20 to 50 10, 20, 30, ...
i = 10/50 10, 11, 12, ...
ITERATORS
DEBUGGING CODE
set trace on (off)
trace the execution of programs for error checking
foreach x of varlist var1 var2 var3 {
command `x', option
}
open brace must
appear on first line
temporary variable used
only within the loop
objects to repeat over
close brace must appear
on final line by itself
command(s) you want to repeat
can be one line or many
...
requires local macro notation
FOREACH: REPEAT COMMANDS OVER STRINGS, LISTS, OR VARIABLES
FORVALUES: REPEAT COMMANDS OVER LISTS OF NUMBERS
display 10
display 20
...
display length("Dr. Nick")
display length("Dr. Hibbert")
When calling a command that takes a string,
surround the macro name with quotes.
foreach x in "Dr. Nick" "Dr. Hibbert" {
display length ( "` x '" )
}
LISTS
sysuse "auto.dta", clear
tab rep78, missing
sysuse "auto2.dta", clear
tab rep78, missing
same as...
loops repeat the same command
over different arguments:
foreach x in auto.dta auto2.dta {
sysuse "`x'", clear
tab rep78, missing
}
STRINGS
summarize mpg
summarize weight
• foreach in takes any list
as an argument with
elements separated by
spaces
• foreach of requires you
to state the list type,
which makes it faster
foreach x in mpg weight {
summarize `x'
}
foreach x of varlist mpg weight {
summarize `x'
}
must define list type
VARIABLES
Use display command to
show the iterator value at
each step in the loop
foreach x in|of [ local, global, varlist, newlist, numlist ] {
Stata commands referring to `x'
}
list types: objects over which the
commands will be repeated
forvalues i = 10(10)50 {
display `i'
}
numeric values over
which loop will run
iterator
Additional Programming Resources
install a package from a Github repository
net install package, from (https://raw.githubusercontent.com/username/repo/master)
download all examples from this cheat sheet in a .do file
bit.ly/statacode
https://github.com/andrewheiss/SublimeStataEnhanced
configure Sublime text for Stata 11-14
adolist
List/copy user-written .ado files
adoupdate
Update user-written .ado files
ssc install adolist
The estout and outreg2 packages provide numerous, flexible options for making tables
after estimation commands. See also putexcel command.
EXPORTING RESULTS
esttab using “auto_reg.txt”, replace plain se
export summary table to a text file, include standard errors
outreg2 [est1 est2] using “auto_reg2.txt”, see replace
export summary table to a text file using outreg2 syntax
esttab est1 est2, se star(* 0.10 ** 0.05 *** 0.01) label
create summary table with standard errors and labels
Access & Save Stored r- and e-class Objects4
mean price
returns list of scalars, macros,
matrices and functions
summarize price, detail
returns a list of scalars
return list ereturn lister
Many Stata commands store results in types of lists. To access these, use return or
ereturn commands. Stored results can be scalars, macros, matrices or functions.
create a temporary copy of active dataframepreserve
restore temporary copy to original pointrestore
create a new variable equal to
average of price
generate p_mean = r(mean)
scalars:
e(df_r) = 73
e(N_over) = 1
e(k_eq) = 1
e(rank) = 1
e(N) = 73
scalars:
...
r(N) = 74
r(sd) = 2949.49...
r(mean) = 6165.25...
r(Var) = 86995225.97...
create a new variable equal to
obs. in estimation command
generate meanN = e(N)
Results are replaced
each time an r-class
/ e-class command
is called
set restore points to test
code that changes data
create local variable called myLocal with the
strings price mpg and length
local myLocal price mpg length
levelsof rep78, local(levels)
create a sorted list of distinct values of rep78,
store results in a local macro called levels
summarize ` myLocal '
summarize contents of local myLocal
add a ` before and a ' after local macro name to call
PRIVATEavailable only in programs, loops, or .do filesLOCALS
local varLab: variable label foreign
store the variable label for foreign in the local varLab
can also do with value labels
tempfile myAuto
save `myAuto'
create a temporary file to
be used within a program
tempvar temp1
generate `temp1' = mpg^2
summarize `temp1'
initialize a new temporary variable called temp1
summarize the temporary variable temp1
save squared mpg values in temp1
special locals for loops/programsTEMPVARS & TEMPFILES
Macros3 public or private variables storing text
global pathdata "C:/Users/SantasLittleHelper/Stata"
define a global variable called pathdata
available through Stata sessions PUBLICGLOBALS
global myGlobal price mpg length
summarize $myGlobal
summarize price mpg length using global
cd $pathdata
change working directory by calling global macro
add a $ before calling a global macro
see also
tempname
matselrc b x, c(1 3)
select columns 1 & 3 of matrix b & store in new matrix x
findit matselrc
mat2txt, matrix(ad1) saving(textfile.txt) replace
ssc install mat2txtexport a matrix to a text file
Matrices2 e-class results are stored as matrices
matrix ad1 = a  d
row bind matrices
matrix ad2 = a , d
column bind matrices
matrix a = (4 5 6)
create a 3 x 1 matrix
matrix b = (7, 8, 9)
create a 1 x 3 matrix
matrix d = b' transpose matrix b; store in d
scalar a1 = “I am a string scalar”
create a scalar a1 storing a string
Scalars1 both r- and e-class results contain scalars
scalar x1 = 3
create a scalar x1 storing the number 3
Scalars can hold
numeric values or
arbitrarily long strings
DISPLAYING & DELETING BUILDING BLOCKS
[scalar | matrix | macro | estimates] [list | drop] b
list contents of object b or drop (delete) object b
[scalar | matrix | macro | estimates] dir
list all defined objects for that class
list contents of matrix b
matrix list b
list all matrices
matrix dir
delete scalar x1
scalar drop x1
Use estimates store
to compile results
for later use
estimates table est1 est2 est3
print a table of the two estimation results est1 and est2
estimates store est1
store previous estimation results est1 in memory
regress price weight
eststo est2: regress price weight mpg
eststo est3: regress price weight mpg foreign
estimate two regression models and store estimation results
ssc install estout
ACCESSING ESTIMATION RESULTS
After you run any estimation command, the results of the estimates are
stored in a structure that you can save, view, compare, and export
basic components of programming
2 rectangular array of quantities or expressions
3 pointers that store text (global or local)
1
MATRICES
MACROS
SCALARS individual numbers or strings
R- AND E-CLASS:Stata stores calculation results in two*
main classes:
r ereturn results from general commands
such as summary or tabulate
return results from estimation
commands such as regress or mean
To assign values to individual variables use:
e
e
r
Building Blocks
* there’s also s- and n-class

Más contenido relacionado

La actualidad más candente

0 1 knapsack using branch and bound
0 1 knapsack using branch and bound0 1 knapsack using branch and bound
0 1 knapsack using branch and boundAbhishek Singh
 
Longest common subsequence
Longest common subsequenceLongest common subsequence
Longest common subsequenceKiran K
 
Theory of computing
Theory of computingTheory of computing
Theory of computingRanjan Kumar
 
Bellman ford algorithm
Bellman ford algorithmBellman ford algorithm
Bellman ford algorithmA. S. M. Shafi
 
Longest common subsequence(dynamic programming).
Longest common subsequence(dynamic programming).Longest common subsequence(dynamic programming).
Longest common subsequence(dynamic programming).munawerzareef
 
06 (ok)como libertar um possuído (libertação)
06 (ok)como libertar um possuído (libertação)06 (ok)como libertar um possuído (libertação)
06 (ok)como libertar um possuído (libertação)IGREJA ADCP CAMPOS ELÍSEOS
 
All pair shortest path by Sania Nisar
All pair shortest path by Sania NisarAll pair shortest path by Sania Nisar
All pair shortest path by Sania NisarSania Nisar
 

La actualidad más candente (13)

0 1 knapsack using branch and bound
0 1 knapsack using branch and bound0 1 knapsack using branch and bound
0 1 knapsack using branch and bound
 
Longest common subsequence
Longest common subsequenceLongest common subsequence
Longest common subsequence
 
Functional analysis
Functional analysis Functional analysis
Functional analysis
 
N Queens problem
N Queens problemN Queens problem
N Queens problem
 
Runge-Kutta-Methods.pptx
Runge-Kutta-Methods.pptxRunge-Kutta-Methods.pptx
Runge-Kutta-Methods.pptx
 
2 homework
2 homework2 homework
2 homework
 
Application of dfs
Application of dfsApplication of dfs
Application of dfs
 
Theory of computing
Theory of computingTheory of computing
Theory of computing
 
DEA
DEADEA
DEA
 
Bellman ford algorithm
Bellman ford algorithmBellman ford algorithm
Bellman ford algorithm
 
Longest common subsequence(dynamic programming).
Longest common subsequence(dynamic programming).Longest common subsequence(dynamic programming).
Longest common subsequence(dynamic programming).
 
06 (ok)como libertar um possuído (libertação)
06 (ok)como libertar um possuído (libertação)06 (ok)como libertar um possuído (libertação)
06 (ok)como libertar um possuído (libertação)
 
All pair shortest path by Sania Nisar
All pair shortest path by Sania NisarAll pair shortest path by Sania Nisar
All pair shortest path by Sania Nisar
 

Destacado

Stata Cheat Sheets (all)
Stata Cheat Sheets (all)Stata Cheat Sheets (all)
Stata Cheat Sheets (all)Laura Hughes
 
Stata cheat sheet: data processing
Stata cheat sheet: data processingStata cheat sheet: data processing
Stata cheat sheet: data processingTim Essam
 
Stata cheat sheet: data visualization
Stata cheat sheet: data visualizationStata cheat sheet: data visualization
Stata cheat sheet: data visualizationTim Essam
 
Stata cheat sheet: Data visualization
Stata cheat sheet: Data visualizationStata cheat sheet: Data visualization
Stata cheat sheet: Data visualizationLaura Hughes
 
Stata cheatsheet transformation
Stata cheatsheet transformationStata cheatsheet transformation
Stata cheatsheet transformationLaura Hughes
 
STATA - Probit Analysis
STATA - Probit AnalysisSTATA - Probit Analysis
STATA - Probit Analysisstata_org_uk
 

Destacado (6)

Stata Cheat Sheets (all)
Stata Cheat Sheets (all)Stata Cheat Sheets (all)
Stata Cheat Sheets (all)
 
Stata cheat sheet: data processing
Stata cheat sheet: data processingStata cheat sheet: data processing
Stata cheat sheet: data processing
 
Stata cheat sheet: data visualization
Stata cheat sheet: data visualizationStata cheat sheet: data visualization
Stata cheat sheet: data visualization
 
Stata cheat sheet: Data visualization
Stata cheat sheet: Data visualizationStata cheat sheet: Data visualization
Stata cheat sheet: Data visualization
 
Stata cheatsheet transformation
Stata cheatsheet transformationStata cheatsheet transformation
Stata cheatsheet transformation
 
STATA - Probit Analysis
STATA - Probit AnalysisSTATA - Probit Analysis
STATA - Probit Analysis
 

Similar a Stata Programming Cheat Sheet

Stata cheatsheet programming
Stata cheatsheet programmingStata cheatsheet programming
Stata cheatsheet programmingTim Essam
 
Cheat Sheet for Stata v15.00 PDF Complete
Cheat Sheet for Stata v15.00 PDF CompleteCheat Sheet for Stata v15.00 PDF Complete
Cheat Sheet for Stata v15.00 PDF CompleteTsamaraLuthfia1
 
Matlab Functions
Matlab FunctionsMatlab Functions
Matlab FunctionsUmer Azeem
 
4 R Tutorial DPLYR Apply Function
4 R Tutorial DPLYR Apply Function4 R Tutorial DPLYR Apply Function
4 R Tutorial DPLYR Apply FunctionSakthi Dasans
 
Introduction to r studio on aws 2020 05_06
Introduction to r studio on aws 2020 05_06Introduction to r studio on aws 2020 05_06
Introduction to r studio on aws 2020 05_06Barry DeCicco
 
Underscore.js
Underscore.jsUnderscore.js
Underscore.jstimourian
 
scala.reflect, Eugene Burmako
scala.reflect, Eugene Burmakoscala.reflect, Eugene Burmako
scala.reflect, Eugene BurmakoVasil Remeniuk
 
Евгений Бурмако «scala.reflect»
Евгений Бурмако «scala.reflect»Евгений Бурмако «scala.reflect»
Евгений Бурмако «scala.reflect»e-Legion
 
Functions in C++
Functions in C++Functions in C++
Functions in C++home
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side JavascriptJulie Iskander
 
CSC8503 Principles of Programming Languages Semester 1, 2015.docx
CSC8503 Principles of Programming Languages Semester 1, 2015.docxCSC8503 Principles of Programming Languages Semester 1, 2015.docx
CSC8503 Principles of Programming Languages Semester 1, 2015.docxfaithxdunce63732
 

Similar a Stata Programming Cheat Sheet (20)

Stata cheatsheet programming
Stata cheatsheet programmingStata cheatsheet programming
Stata cheatsheet programming
 
Matlab Manual
Matlab ManualMatlab Manual
Matlab Manual
 
Cheat Sheet for Stata v15.00 PDF Complete
Cheat Sheet for Stata v15.00 PDF CompleteCheat Sheet for Stata v15.00 PDF Complete
Cheat Sheet for Stata v15.00 PDF Complete
 
INTRODUCTION TO STATA.pptx
INTRODUCTION TO STATA.pptxINTRODUCTION TO STATA.pptx
INTRODUCTION TO STATA.pptx
 
Matlab Functions
Matlab FunctionsMatlab Functions
Matlab Functions
 
4 R Tutorial DPLYR Apply Function
4 R Tutorial DPLYR Apply Function4 R Tutorial DPLYR Apply Function
4 R Tutorial DPLYR Apply Function
 
Mysql1
Mysql1Mysql1
Mysql1
 
Practical cats
Practical catsPractical cats
Practical cats
 
Introduction to r studio on aws 2020 05_06
Introduction to r studio on aws 2020 05_06Introduction to r studio on aws 2020 05_06
Introduction to r studio on aws 2020 05_06
 
MatlabIntro (1).ppt
MatlabIntro (1).pptMatlabIntro (1).ppt
MatlabIntro (1).ppt
 
Underscore.js
Underscore.jsUnderscore.js
Underscore.js
 
scala.reflect, Eugene Burmako
scala.reflect, Eugene Burmakoscala.reflect, Eugene Burmako
scala.reflect, Eugene Burmako
 
Евгений Бурмако «scala.reflect»
Евгений Бурмако «scala.reflect»Евгений Бурмако «scala.reflect»
Евгений Бурмако «scala.reflect»
 
What is new in Java 8
What is new in Java 8What is new in Java 8
What is new in Java 8
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side Javascript
 
Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
 
Aggregate.pptx
Aggregate.pptxAggregate.pptx
Aggregate.pptx
 
Spark workshop
Spark workshopSpark workshop
Spark workshop
 
CSC8503 Principles of Programming Languages Semester 1, 2015.docx
CSC8503 Principles of Programming Languages Semester 1, 2015.docxCSC8503 Principles of Programming Languages Semester 1, 2015.docx
CSC8503 Principles of Programming Languages Semester 1, 2015.docx
 

Último

April 2024 - Crypto Market Report's Analysis
April 2024 - Crypto Market Report's AnalysisApril 2024 - Crypto Market Report's Analysis
April 2024 - Crypto Market Report's Analysismanisha194592
 
Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...
Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...
Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...amitlee9823
 
BDSM⚡Call Girls in Mandawali Delhi >༒8448380779 Escort Service
BDSM⚡Call Girls in Mandawali Delhi >༒8448380779 Escort ServiceBDSM⚡Call Girls in Mandawali Delhi >༒8448380779 Escort Service
BDSM⚡Call Girls in Mandawali Delhi >༒8448380779 Escort ServiceDelhi Call girls
 
Zuja dropshipping via API with DroFx.pptx
Zuja dropshipping via API with DroFx.pptxZuja dropshipping via API with DroFx.pptx
Zuja dropshipping via API with DroFx.pptxolyaivanovalion
 
Cheap Rate Call girls Sarita Vihar Delhi 9205541914 shot 1500 night
Cheap Rate Call girls Sarita Vihar Delhi 9205541914 shot 1500 nightCheap Rate Call girls Sarita Vihar Delhi 9205541914 shot 1500 night
Cheap Rate Call girls Sarita Vihar Delhi 9205541914 shot 1500 nightDelhi Call girls
 
Vip Model Call Girls (Delhi) Karol Bagh 9711199171✔️Body to body massage wit...
Vip Model  Call Girls (Delhi) Karol Bagh 9711199171✔️Body to body massage wit...Vip Model  Call Girls (Delhi) Karol Bagh 9711199171✔️Body to body massage wit...
Vip Model Call Girls (Delhi) Karol Bagh 9711199171✔️Body to body massage wit...shivangimorya083
 
Discover Why Less is More in B2B Research
Discover Why Less is More in B2B ResearchDiscover Why Less is More in B2B Research
Discover Why Less is More in B2B Researchmichael115558
 
FESE Capital Markets Fact Sheet 2024 Q1.pdf
FESE Capital Markets Fact Sheet 2024 Q1.pdfFESE Capital Markets Fact Sheet 2024 Q1.pdf
FESE Capital Markets Fact Sheet 2024 Q1.pdfMarinCaroMartnezBerg
 
Week-01-2.ppt BBB human Computer interaction
Week-01-2.ppt BBB human Computer interactionWeek-01-2.ppt BBB human Computer interaction
Week-01-2.ppt BBB human Computer interactionfulawalesam
 
100-Concepts-of-AI by Anupama Kate .pptx
100-Concepts-of-AI by Anupama Kate .pptx100-Concepts-of-AI by Anupama Kate .pptx
100-Concepts-of-AI by Anupama Kate .pptxAnupama Kate
 
Call Girls Indiranagar Just Call 👗 7737669865 👗 Top Class Call Girl Service B...
Call Girls Indiranagar Just Call 👗 7737669865 👗 Top Class Call Girl Service B...Call Girls Indiranagar Just Call 👗 7737669865 👗 Top Class Call Girl Service B...
Call Girls Indiranagar Just Call 👗 7737669865 👗 Top Class Call Girl Service B...amitlee9823
 
BabyOno dropshipping via API with DroFx.pptx
BabyOno dropshipping via API with DroFx.pptxBabyOno dropshipping via API with DroFx.pptx
BabyOno dropshipping via API with DroFx.pptxolyaivanovalion
 
Call Girls Hsr Layout Just Call 👗 7737669865 👗 Top Class Call Girl Service Ba...
Call Girls Hsr Layout Just Call 👗 7737669865 👗 Top Class Call Girl Service Ba...Call Girls Hsr Layout Just Call 👗 7737669865 👗 Top Class Call Girl Service Ba...
Call Girls Hsr Layout Just Call 👗 7737669865 👗 Top Class Call Girl Service Ba...amitlee9823
 
Al Barsha Escorts $#$ O565212860 $#$ Escort Service In Al Barsha
Al Barsha Escorts $#$ O565212860 $#$ Escort Service In Al BarshaAl Barsha Escorts $#$ O565212860 $#$ Escort Service In Al Barsha
Al Barsha Escorts $#$ O565212860 $#$ Escort Service In Al BarshaAroojKhan71
 
Smarteg dropshipping via API with DroFx.pptx
Smarteg dropshipping via API with DroFx.pptxSmarteg dropshipping via API with DroFx.pptx
Smarteg dropshipping via API with DroFx.pptxolyaivanovalion
 
Market Analysis in the 5 Largest Economic Countries in Southeast Asia.pdf
Market Analysis in the 5 Largest Economic Countries in Southeast Asia.pdfMarket Analysis in the 5 Largest Economic Countries in Southeast Asia.pdf
Market Analysis in the 5 Largest Economic Countries in Southeast Asia.pdfRachmat Ramadhan H
 
Log Analysis using OSSEC sasoasasasas.pptx
Log Analysis using OSSEC sasoasasasas.pptxLog Analysis using OSSEC sasoasasasas.pptx
Log Analysis using OSSEC sasoasasasas.pptxJohnnyPlasten
 

Último (20)

April 2024 - Crypto Market Report's Analysis
April 2024 - Crypto Market Report's AnalysisApril 2024 - Crypto Market Report's Analysis
April 2024 - Crypto Market Report's Analysis
 
Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...
Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...
Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...
 
BDSM⚡Call Girls in Mandawali Delhi >༒8448380779 Escort Service
BDSM⚡Call Girls in Mandawali Delhi >༒8448380779 Escort ServiceBDSM⚡Call Girls in Mandawali Delhi >༒8448380779 Escort Service
BDSM⚡Call Girls in Mandawali Delhi >༒8448380779 Escort Service
 
Zuja dropshipping via API with DroFx.pptx
Zuja dropshipping via API with DroFx.pptxZuja dropshipping via API with DroFx.pptx
Zuja dropshipping via API with DroFx.pptx
 
Cheap Rate Call girls Sarita Vihar Delhi 9205541914 shot 1500 night
Cheap Rate Call girls Sarita Vihar Delhi 9205541914 shot 1500 nightCheap Rate Call girls Sarita Vihar Delhi 9205541914 shot 1500 night
Cheap Rate Call girls Sarita Vihar Delhi 9205541914 shot 1500 night
 
Vip Model Call Girls (Delhi) Karol Bagh 9711199171✔️Body to body massage wit...
Vip Model  Call Girls (Delhi) Karol Bagh 9711199171✔️Body to body massage wit...Vip Model  Call Girls (Delhi) Karol Bagh 9711199171✔️Body to body massage wit...
Vip Model Call Girls (Delhi) Karol Bagh 9711199171✔️Body to body massage wit...
 
Discover Why Less is More in B2B Research
Discover Why Less is More in B2B ResearchDiscover Why Less is More in B2B Research
Discover Why Less is More in B2B Research
 
FESE Capital Markets Fact Sheet 2024 Q1.pdf
FESE Capital Markets Fact Sheet 2024 Q1.pdfFESE Capital Markets Fact Sheet 2024 Q1.pdf
FESE Capital Markets Fact Sheet 2024 Q1.pdf
 
CHEAP Call Girls in Saket (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Saket (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Saket (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Saket (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Week-01-2.ppt BBB human Computer interaction
Week-01-2.ppt BBB human Computer interactionWeek-01-2.ppt BBB human Computer interaction
Week-01-2.ppt BBB human Computer interaction
 
100-Concepts-of-AI by Anupama Kate .pptx
100-Concepts-of-AI by Anupama Kate .pptx100-Concepts-of-AI by Anupama Kate .pptx
100-Concepts-of-AI by Anupama Kate .pptx
 
Call Girls Indiranagar Just Call 👗 7737669865 👗 Top Class Call Girl Service B...
Call Girls Indiranagar Just Call 👗 7737669865 👗 Top Class Call Girl Service B...Call Girls Indiranagar Just Call 👗 7737669865 👗 Top Class Call Girl Service B...
Call Girls Indiranagar Just Call 👗 7737669865 👗 Top Class Call Girl Service B...
 
BabyOno dropshipping via API with DroFx.pptx
BabyOno dropshipping via API with DroFx.pptxBabyOno dropshipping via API with DroFx.pptx
BabyOno dropshipping via API with DroFx.pptx
 
Call Girls Hsr Layout Just Call 👗 7737669865 👗 Top Class Call Girl Service Ba...
Call Girls Hsr Layout Just Call 👗 7737669865 👗 Top Class Call Girl Service Ba...Call Girls Hsr Layout Just Call 👗 7737669865 👗 Top Class Call Girl Service Ba...
Call Girls Hsr Layout Just Call 👗 7737669865 👗 Top Class Call Girl Service Ba...
 
Sampling (random) method and Non random.ppt
Sampling (random) method and Non random.pptSampling (random) method and Non random.ppt
Sampling (random) method and Non random.ppt
 
Al Barsha Escorts $#$ O565212860 $#$ Escort Service In Al Barsha
Al Barsha Escorts $#$ O565212860 $#$ Escort Service In Al BarshaAl Barsha Escorts $#$ O565212860 $#$ Escort Service In Al Barsha
Al Barsha Escorts $#$ O565212860 $#$ Escort Service In Al Barsha
 
(NEHA) Call Girls Katra Call Now 8617697112 Katra Escorts 24x7
(NEHA) Call Girls Katra Call Now 8617697112 Katra Escorts 24x7(NEHA) Call Girls Katra Call Now 8617697112 Katra Escorts 24x7
(NEHA) Call Girls Katra Call Now 8617697112 Katra Escorts 24x7
 
Smarteg dropshipping via API with DroFx.pptx
Smarteg dropshipping via API with DroFx.pptxSmarteg dropshipping via API with DroFx.pptx
Smarteg dropshipping via API with DroFx.pptx
 
Market Analysis in the 5 Largest Economic Countries in Southeast Asia.pdf
Market Analysis in the 5 Largest Economic Countries in Southeast Asia.pdfMarket Analysis in the 5 Largest Economic Countries in Southeast Asia.pdf
Market Analysis in the 5 Largest Economic Countries in Southeast Asia.pdf
 
Log Analysis using OSSEC sasoasasasas.pptx
Log Analysis using OSSEC sasoasasasas.pptxLog Analysis using OSSEC sasoasasasas.pptx
Log Analysis using OSSEC sasoasasasas.pptx
 

Stata Programming Cheat Sheet

  • 1. Programming Cheat Sheetwith Stata 14.1 For more info see Stata’s reference manual (stata.com) Tim Essam (tessam@usaid.gov) • Laura Hughes (lhughes@usaid.gov) follow us @StataRGIS and @flaneuseks inspired by RStudio’s awesome Cheat Sheets (rstudio.com/resources/cheatsheets) updated June 2016 CC BY 4.0 geocenter.github.io/StataTraining Disclaimer: we are not affiliated with Stata. But we like it. PUTTING IT ALL TOGETHER sysuse auto, clear generate car_make = word(make, 1) levelsof car_make, local(cmake) local i = 1 local cmake_len : word count `cmake' foreach x of local cmake { display in yellow "Make group `i' is `x'" if `i' == `cmake_len' { display "The total number of groups is `i'" } local i = `++i' } define the local i to be an iterator tests the position of the iterator, executes contents in brackets when the condition is true increment iterator by one store the length of local cmake in local cmake_len calculate unique groups of car_make and store in local cmake pull out the first word from the make variable see also capture and scalar _rc Stata has three options for repeating commands over lists or values: foreach, forvalues, and while. Though each has a different first line, the syntax is consistent: Loops: Automate Repetitive Tasks ANATOMY OF A LOOP see also while i = 10(10)50 10, 20, 30, ... i = 10 20 to 50 10, 20, 30, ... i = 10/50 10, 11, 12, ... ITERATORS DEBUGGING CODE set trace on (off) trace the execution of programs for error checking foreach x of varlist var1 var2 var3 { command `x', option } open brace must appear on first line temporary variable used only within the loop objects to repeat over close brace must appear on final line by itself command(s) you want to repeat can be one line or many ... requires local macro notation FOREACH: REPEAT COMMANDS OVER STRINGS, LISTS, OR VARIABLES FORVALUES: REPEAT COMMANDS OVER LISTS OF NUMBERS display 10 display 20 ... display length("Dr. Nick") display length("Dr. Hibbert") When calling a command that takes a string, surround the macro name with quotes. foreach x in "Dr. Nick" "Dr. Hibbert" { display length ( "` x '" ) } LISTS sysuse "auto.dta", clear tab rep78, missing sysuse "auto2.dta", clear tab rep78, missing same as... loops repeat the same command over different arguments: foreach x in auto.dta auto2.dta { sysuse "`x'", clear tab rep78, missing } STRINGS summarize mpg summarize weight • foreach in takes any list as an argument with elements separated by spaces • foreach of requires you to state the list type, which makes it faster foreach x in mpg weight { summarize `x' } foreach x of varlist mpg weight { summarize `x' } must define list type VARIABLES Use display command to show the iterator value at each step in the loop foreach x in|of [ local, global, varlist, newlist, numlist ] { Stata commands referring to `x' } list types: objects over which the commands will be repeated forvalues i = 10(10)50 { display `i' } numeric values over which loop will run iterator Additional Programming Resources install a package from a Github repository net install package, from (https://raw.githubusercontent.com/username/repo/master) download all examples from this cheat sheet in a .do file bit.ly/statacode https://github.com/andrewheiss/SublimeStataEnhanced configure Sublime text for Stata 11-14 adolist List/copy user-written .ado files adoupdate Update user-written .ado files ssc install adolist The estout and outreg2 packages provide numerous, flexible options for making tables after estimation commands. See also putexcel command. EXPORTING RESULTS esttab using “auto_reg.txt”, replace plain se export summary table to a text file, include standard errors outreg2 [est1 est2] using “auto_reg2.txt”, see replace export summary table to a text file using outreg2 syntax esttab est1 est2, se star(* 0.10 ** 0.05 *** 0.01) label create summary table with standard errors and labels Access & Save Stored r- and e-class Objects4 mean price returns list of scalars, macros, matrices and functions summarize price, detail returns a list of scalars return list ereturn lister Many Stata commands store results in types of lists. To access these, use return or ereturn commands. Stored results can be scalars, macros, matrices or functions. create a temporary copy of active dataframepreserve restore temporary copy to original pointrestore create a new variable equal to average of price generate p_mean = r(mean) scalars: e(df_r) = 73 e(N_over) = 1 e(k_eq) = 1 e(rank) = 1 e(N) = 73 scalars: ... r(N) = 74 r(sd) = 2949.49... r(mean) = 6165.25... r(Var) = 86995225.97... create a new variable equal to obs. in estimation command generate meanN = e(N) Results are replaced each time an r-class / e-class command is called set restore points to test code that changes data create local variable called myLocal with the strings price mpg and length local myLocal price mpg length levelsof rep78, local(levels) create a sorted list of distinct values of rep78, store results in a local macro called levels summarize ` myLocal ' summarize contents of local myLocal add a ` before and a ' after local macro name to call PRIVATEavailable only in programs, loops, or .do filesLOCALS local varLab: variable label foreign store the variable label for foreign in the local varLab can also do with value labels tempfile myAuto save `myAuto' create a temporary file to be used within a program tempvar temp1 generate `temp1' = mpg^2 summarize `temp1' initialize a new temporary variable called temp1 summarize the temporary variable temp1 save squared mpg values in temp1 special locals for loops/programsTEMPVARS & TEMPFILES Macros3 public or private variables storing text global pathdata "C:/Users/SantasLittleHelper/Stata" define a global variable called pathdata available through Stata sessions PUBLICGLOBALS global myGlobal price mpg length summarize $myGlobal summarize price mpg length using global cd $pathdata change working directory by calling global macro add a $ before calling a global macro see also tempname matselrc b x, c(1 3) select columns 1 & 3 of matrix b & store in new matrix x findit matselrc mat2txt, matrix(ad1) saving(textfile.txt) replace ssc install mat2txtexport a matrix to a text file Matrices2 e-class results are stored as matrices matrix ad1 = a d row bind matrices matrix ad2 = a , d column bind matrices matrix a = (4 5 6) create a 3 x 1 matrix matrix b = (7, 8, 9) create a 1 x 3 matrix matrix d = b' transpose matrix b; store in d scalar a1 = “I am a string scalar” create a scalar a1 storing a string Scalars1 both r- and e-class results contain scalars scalar x1 = 3 create a scalar x1 storing the number 3 Scalars can hold numeric values or arbitrarily long strings DISPLAYING & DELETING BUILDING BLOCKS [scalar | matrix | macro | estimates] [list | drop] b list contents of object b or drop (delete) object b [scalar | matrix | macro | estimates] dir list all defined objects for that class list contents of matrix b matrix list b list all matrices matrix dir delete scalar x1 scalar drop x1 Use estimates store to compile results for later use estimates table est1 est2 est3 print a table of the two estimation results est1 and est2 estimates store est1 store previous estimation results est1 in memory regress price weight eststo est2: regress price weight mpg eststo est3: regress price weight mpg foreign estimate two regression models and store estimation results ssc install estout ACCESSING ESTIMATION RESULTS After you run any estimation command, the results of the estimates are stored in a structure that you can save, view, compare, and export basic components of programming 2 rectangular array of quantities or expressions 3 pointers that store text (global or local) 1 MATRICES MACROS SCALARS individual numbers or strings R- AND E-CLASS:Stata stores calculation results in two* main classes: r ereturn results from general commands such as summary or tabulate return results from estimation commands such as regress or mean To assign values to individual variables use: e e r Building Blocks * there’s also s- and n-class