Stata Skill
You have access to comprehensive Stata reference files. Do not load all files.
Read only the 1-3 files relevant to the user's current task using the routing table below.
Critical Gotchas
These are Stata-specific pitfalls that lead to silent bugs. Internalize these before writing any code.
Missing Values Sort to +Infinity
Stata's . (and .a-.z) are greater than all numbers.
* WRONG — includes observations where income is missing!
gen high_income = (income > 50000)
* RIGHT
gen high_income = (income > 50000) if !missing(income)
* WRONG — missing ages appear in this list
list if age > 60
* RIGHT
list if age > 60 & !missing(age)
= vs ==
= is assignment; == is comparison. Mixing them up is a syntax error or silent bug.
* WRONG — syntax error
gen employed = 1 if status = 1
* RIGHT
gen employed = 1 if status == 1
Local Macro Syntax
Locals use `name' (backtick + single-quote). Globals use $name or ${name}.
Forgetting the closing quote is the #1 macro bug.
local controls "age education income"
regress wage `controls' // correct
regress wage `controls // WRONG — missing closing quote
regress wage 'controls' // WRONG — wrong quote characters
by Requires Prior Sort (Use bysort)
* WRONG — error if data not sorted by id
by id: gen first = (_n == 1)
* RIGHT — bysort sorts automatically
bysort id: gen first = (_n == 1)
* Also RIGHT — explicit sort
sort id
by id: gen first = (_n == 1)
Factor Variable Notation (i. and c.)
Use i. for categorical, c. for continuous. Omitting i. treats categories as continuous.
* WRONG — treats race as continuous (e.g., race=3 has 3x effect of race=1)
regress wage race education
* RIGHT — creates dummies automatically
regress wage i.race education
* Interactions
regress wage i.race##c.education // full interaction
regress wage i.race#c.education // interaction only (no main effects)
generate vs replace
generate creates new variables; replace modifies existing ones. Using generate on an existing variable name is an error.
gen x = 1
gen x = 2 // ERROR: x already defined
replace x = 2 // correct
String Comparison Is Case-Sensitive
* May miss "Male", "MALE", etc.
keep if gender == "male"
* Safer
keep if lower(gender) == "male"
merge Always Check _merge
merge 1:1 id using other.dta
tab _merge // always inspect
assert _merge == 3 // or handle mismatches
drop _merge
preserve / restore for Temporary Changes
preserve
collapse (mean) income, by(state)
* ... do something with collapsed data ...
restore // original data is back
Weights Are Not Interchangeable
fweight — frequency weights (replication)
aweight — analytic/regression weights (inverse variance)
pweight — probability/sampling weights (survey data, implies robust SE)
iweight — importance weights (rarely used)
capture Swallows Errors
capture some_command
if _rc != 0 {
di as error "Failed with code: " _rc
exit _rc
}
Line Continuation Uses ///
regress y x1 x2 x3 ///
x4 x5 x6, ///
vce(robust)
Stored Results: r() vs e() vs s()
r() — r-class commands (summarize, tabulate, etc.)
e() — e-class commands (estimation: regress, logit, etc.)
s() — s-class commands (parsing)
A new estimation command overwrites previous e() results. Store them first:
regress y x1 x2
estimates store model1
Routing Table
Read only the files relevant to the user's task. Paths are relative to this SKILL.md file.
Data Operations
| File |
Topics & Key Commands |
references/basics-getting-started.md |
use, save, describe, browse, sysuse, basic workflow |
references/data-import-export.md |
import delimited, import excel, ODBC, export, web data |
references/data-management.md |
generate, replace, merge, append, reshape, collapse, recode, egen, encode/decode |
references/variables-operators.md |
Variable types, byte/int/long/float/double, operators, missing values (.<.a), if/in qualifiers |
references/string-functions.md |
substr(), regexm(), strtrim(), split, ustrlen(), regex, Unicode |
references/date-time-functions.md |
date(), clock(), %td/%tc formats, mdy(), dofm(), business calendars |
references/mathematical-functions.md |
round(), log(), exp(), abs(), mod(), cond(), distributions, random numbers |
Statistics & Econometrics
| File |
Topics & Key Commands |
references/descriptive-statistics.md |
summarize, tabulate, correlate, tabstat, codebook, weighted stats |
references/linear-regression.md |
regress, vce(robust), vce(cluster), test, lincom, margins, predict, ivregress |
references/panel-data.md |
xtset, xtreg fe/re, Hausman test, xtabond, dynamic panels |
references/time-series.md |
tsset, ARIMA, VAR, dfuller, pperron, irf, forecasting |
references/limited-dependent-variables.md |
logit, probit, tobit, poisson, nbreg, mlogit, ologit, margins for nonlinear |
references/bootstrap-simulation.md |
bootstrap, simulate, permute, Monte Carlo |
references/survey-data-analysis.md |
svyset, svy:, subpop(), complex survey design, replicate weights |
references/missing-data-handling.md |
mi impute, mi estimate, FIML, misstable, diagnostics |
references/maximum-likelihood.md |
ml model, custom likelihood functions, ml init, gradient-based optimization |
references/gmm-estimation.md |
gmm, moment conditions, estat overid, J-test |
Causal Inference
| File |
Topics & Key Commands |
references/treatment-effects.md |
teffects ra/ipw/ipwra/aipw, stteffects, ATE/ATT/ATET |
references/difference-in-differences.md |
DiD, parallel trends, event studies, staggered adoption |
references/regression-discontinuity.md |
Sharp/fuzzy RD, bandwidth selection, rdplot |
references/matching-methods.md |
PSM, nearest neighbor, kernel matching, teffects nnmatch |
references/sample-selection.md |
heckman, heckprobit, treatment models, exclusion restrictions |
Advanced Methods
| File |
Topics & Key Commands |
references/survival-analysis.md |
stset, stcox, streg, Kaplan-Meier, parametric models |
references/sem-factor-analysis.md |
sem, gsem, CFA, path analysis, alpha, reliability |
references/nonparametric-methods.md |
kdensity, rank tests, qreg, npregress |
references/spatial-analysis.md |
spmatrix, spregress, spatial weights, Moran's I |
references/machine-learning.md |
lasso, elasticnet, cvlasso, cross-validation |
Graphics
| File |
Topics & Key Commands |
references/graphics.md |
twoway, scatter, line, bar, histogram, graph combine, graph export, schemes |
Programming
| File |
Topics & Key Commands |
references/programming-basics.md |
local, global, foreach, forvalues, program define, syntax, return |
references/advanced-programming.md |
syntax, mata, classes, _prefix, dialog boxes, tempfile/tempvar |
references/mata-introduction.md |
Mata basics, when to use Mata vs ado, data types |
references/mata-programming.md |
Mata functions, flow control, structures, pointers |
references/mata-matrix-operations.md |
Matrix creation, decompositions, solvers, st_matrix() |
references/mata-data-access.md |
st_data(), st_view(), st_store(), performance tips |
Output & Workflow
| File |
Topics & Key Commands |
references/tables-reporting.md |
putexcel, putdocx, putpdf, LaTeX integration, collect |
references/workflow-best-practices.md |
Project structure, master do-files, version control, debugging, common mistakes |
references/external-tools-integration.md |
Python via python:, R via rsource, shell commands, Git |
Community Packages
| File |
What It Does |
packages/reghdfe.md |
High-dimensional fixed effects OLS (absorbs multiple FE sets efficiently) |
packages/estout.md |
esttab/estout: publication-quality regression tables |
packages/outreg2.md |
Alternative regression table exporter (Word, Excel, TeX) |
packages/asdoc.md |
One-command Word document creation for any Stata output |
packages/tabout.md |
Cross-tabulations and summary tables to file |
packages/coefplot.md |
Coefficient plots from stored estimates |
packages/graph-schemes.md |
grstyle, schemepack, plotplain — better graph themes |
packages/did.md |
Modern DiD: csdid, did_multiplegt, did_imputation (Callaway-Sant'Anna, de Chaisemartin-D'Haultfoeuille, Borusyak-Jaravel-Spiess) |
packages/event-study.md |
eventstudyinteract, eventdd — event study estimators |
packages/rdrobust.md |
Robust RD estimation with optimal bandwidth (rdrobust, rdplot, rdbwselect) |
packages/psmatch2.md |
Propensity score matching (nearest neighbor, kernel, radius) |
packages/synth.md |
Synthetic control method (synth, synth_runner) |
packages/ivreg2.md |
Enhanced IV/2SLS: ivreg2, xtivreg2 with additional diagnostics |
packages/xtabond2.md |
Dynamic panel GMM (Arellano-Bond/Blundell-Bond) |
packages/binsreg.md |
Binned scatter plots with CI (binsreg, binstest) |
packages/nprobust.md |
Nonparametric kernel estimation and inference |
packages/diagnostics.md |
bacondecomp, xttest3, collinearity, heteroskedasticity tests |
packages/winsor.md |
Winsorizing and trimming: winsor2, winsor |
packages/data-manipulation.md |
gtools (fast collapse/egen), rangestat, egenmore |
packages/package-management.md |
ssc install, net install, ado update, finding packages |
Common Patterns
Regression Table Workflow
* Estimate models
eststo clear
eststo: regress y x1 x2, vce(robust)
eststo: regress y x1 x2 x3, vce(robust)
eststo: regress y x1 x2 x3 x4, vce(cluster id)
* Export table
esttab using "results.tex", replace ///
se star(* 0.10 ** 0.05 *** 0.01) ///
label booktabs ///
title("Main Results") ///
mtitles("(1)" "(2)" "(3)")
Panel Data Setup
xtset panelid timevar // declare panel structure
xtdescribe // check balance
xtsum outcome // within/between variation
* Fixed effects
xtreg y x1 x2, fe vce(cluster panelid)
* Or with reghdfe (preferred for multiple FE)
reghdfe y x1 x2, absorb(panelid timevar) vce(cluster panelid)
Difference-in-Differences
* Classic 2x2 DiD
gen post = (year >= treatment_year)
gen treat_post = treated * post
regress y treated post treat_post, vce(cluster id)
* Modern staggered DiD (Callaway & Sant'Anna)
csdid y x1 x2, ivar(id) time(year) gvar(first_treat) agg(event)
csdid_plot
Graph Export
* Publication-quality scatter with fit line
twoway (scatter y x, mcolor(navy%50) msize(small)) ///
(lfit y x, lcolor(cranberry) lwidth(medthick)), ///
title("Title Here") ///
xtitle("X Label") ytitle("Y Label") ///
legend(off) scheme(s2color)
graph export "figure1.pdf", replace as(pdf)
graph export "figure1.png", replace as(png) width(2400)
Data Cleaning Pipeline
* Load and inspect
import delimited "raw_data.csv", clear varnames(1)
describe
codebook, compact
* Clean
rename *, lower // lowercase all varnames
destring income, replace force // convert string to numeric
replace income = . if income < 0
* Label
label variable income "Annual household income (USD)"
label define yesno 0 "No" 1 "Yes"
label values employed yesno
* Save
compress
save "clean_data.dta", replace
Multiple Imputation
mi set mlong
mi register imputed income education
mi impute chained (regress) income (ologit) education = age i.gender, add(20) rseed(12345)
mi estimate: regress wage income education age i.gender
1---
2name: stata-3
3description: >
4 Comprehensive Stata reference for writing correct .do files, data management,
5 econometrics, causal inference, graphics, Mata programming, and 17+ community
6 packages (reghdfe, estout, did, rdrobust, etc.). Covers syntax, options,
7 gotchas, and idiomatic patterns. Use this skill whenever the user asks you to
8 write, debug, or explain Stata code.
9triggers:
10 - stata
11 - .do file
12 - do-file
13 - regress
14 - regression in stata
15 - panel data
16 - fixed effects
17 - reghdfe
18 - estout
19 - esttab
20 - outreg2
21 - difference-in-differences
22 - event study
23 - propensity score
24 - rdrobust
25 - synthetic control
26 - xtset
27 - merge
28 - reshape
29 - collapse
30 - egen
31 - ssc install
32 - mata
33 - putexcel
34 - putdocx
35 - graph export
36 - survival analysis
37 - heckman
38 - tobit
39 - logit
40 - probit
41 - arima
42 - var model
43 - gmm estimation
44 - bootstrap stata
45 - survey weights
46 - multiple imputation
47 - lasso stata
48---
49
50# Stata Skill
51
52You have access to comprehensive Stata reference files. **Do not load all files.**
53Read only the 1-3 files relevant to the user's current task using the routing table below.
54
55---
56
57## Critical Gotchas
58
59These are Stata-specific pitfalls that lead to silent bugs. Internalize these before writing any code.
60
61### Missing Values Sort to +Infinity
62Stata's `.` (and `.a`-`.z`) are **greater than all numbers**.
63```stata
64* WRONG — includes observations where income is missing!
65gen high_income = (income > 50000)
66
67* RIGHT
68gen high_income = (income > 50000) if !missing(income)
69
70* WRONG — missing ages appear in this list
71list if age > 60
72
73* RIGHT
74list if age > 60 & !missing(age)
75```
76
77### `=` vs `==`
78`=` is assignment; `==` is comparison. Mixing them up is a syntax error or silent bug.
79```stata
80* WRONG — syntax error
81gen employed = 1 if status = 1
82
83* RIGHT
84gen employed = 1 if status == 1
85```
86
87### Local Macro Syntax
88Locals use `` `name' `` (backtick + single-quote). Globals use `$name` or `${name}`.
89Forgetting the closing quote is the #1 macro bug.
90```stata
91local controls "age education income"
92regress wage `controls' // correct
93regress wage `controls // WRONG — missing closing quote
94regress wage 'controls' // WRONG — wrong quote characters
95```
96
97### `by` Requires Prior Sort (Use `bysort`)
98```stata
99* WRONG — error if data not sorted by id
100by id: gen first = (_n == 1)
101
102* RIGHT — bysort sorts automatically
103bysort id: gen first = (_n == 1)
104
105* Also RIGHT — explicit sort
106sort id
107by id: gen first = (_n == 1)
108```
109
110### Factor Variable Notation (`i.` and `c.`)
111Use `i.` for categorical, `c.` for continuous. Omitting `i.` treats categories as continuous.
112```stata
113* WRONG — treats race as continuous (e.g., race=3 has 3x effect of race=1)
114regress wage race education
115
116* RIGHT — creates dummies automatically
117regress wage i.race education
118
119* Interactions
120regress wage i.race##c.education // full interaction
121regress wage i.race#c.education // interaction only (no main effects)
122```
123
124### `generate` vs `replace`
125`generate` creates new variables; `replace` modifies existing ones. Using `generate` on an existing variable name is an error.
126```stata
127gen x = 1
128gen x = 2 // ERROR: x already defined
129replace x = 2 // correct
130```
131
132### String Comparison Is Case-Sensitive
133```stata
134* May miss "Male", "MALE", etc.
135keep if gender == "male"
136
137* Safer
138keep if lower(gender) == "male"
139```
140
141### `merge` Always Check `_merge`
142```stata
143merge 1:1 id using other.dta
144tab _merge // always inspect
145assert _merge == 3 // or handle mismatches
146drop _merge
147```
148
149### `preserve` / `restore` for Temporary Changes
150```stata
151preserve
152collapse (mean) income, by(state)
153* ... do something with collapsed data ...
154restore // original data is back
155```
156
157### Weights Are Not Interchangeable
158- `fweight` — frequency weights (replication)
159- `aweight` — analytic/regression weights (inverse variance)
160- `pweight` — probability/sampling weights (survey data, implies robust SE)
161- `iweight` — importance weights (rarely used)
162
163### `capture` Swallows Errors
164```stata
165capture some_command
166if _rc != 0 {
167 di as error "Failed with code: " _rc
168 exit _rc
169}
170```
171
172### Line Continuation Uses `///`
173```stata
174regress y x1 x2 x3 ///
175 x4 x5 x6, ///
176 vce(robust)
177```
178
179### Stored Results: `r()` vs `e()` vs `s()`
180- `r()` — r-class commands (summarize, tabulate, etc.)
181- `e()` — e-class commands (estimation: regress, logit, etc.)
182- `s()` — s-class commands (parsing)
183
184A new estimation command **overwrites** previous `e()` results. Store them first:
185```stata
186regress y x1 x2
187estimates store model1
188```
189
190---
191
192## Routing Table
193
194Read only the files relevant to the user's task. Paths are relative to this SKILL.md file.
195
196### Data Operations
197| File | Topics & Key Commands |
198|------|----------------------|
199| `references/basics-getting-started.md` | `use`, `save`, `describe`, `browse`, `sysuse`, basic workflow |
200| `references/data-import-export.md` | `import delimited`, `import excel`, ODBC, `export`, web data |
201| `references/data-management.md` | `generate`, `replace`, `merge`, `append`, `reshape`, `collapse`, `recode`, `egen`, `encode`/`decode` |
202| `references/variables-operators.md` | Variable types, `byte`/`int`/`long`/`float`/`double`, operators, missing values (`.<.a`), `if`/`in` qualifiers |
203| `references/string-functions.md` | `substr()`, `regexm()`, `strtrim()`, `split`, `ustrlen()`, regex, Unicode |
204| `references/date-time-functions.md` | `date()`, `clock()`, `%td`/`%tc` formats, `mdy()`, `dofm()`, business calendars |
205| `references/mathematical-functions.md` | `round()`, `log()`, `exp()`, `abs()`, `mod()`, `cond()`, distributions, random numbers |
206
207### Statistics & Econometrics
208| File | Topics & Key Commands |
209|------|----------------------|
210| `references/descriptive-statistics.md` | `summarize`, `tabulate`, `correlate`, `tabstat`, `codebook`, weighted stats |
211| `references/linear-regression.md` | `regress`, `vce(robust)`, `vce(cluster)`, `test`, `lincom`, `margins`, `predict`, `ivregress` |
212| `references/panel-data.md` | `xtset`, `xtreg fe`/`re`, Hausman test, `xtabond`, dynamic panels |
213| `references/time-series.md` | `tsset`, ARIMA, VAR, `dfuller`, `pperron`, `irf`, forecasting |
214| `references/limited-dependent-variables.md` | `logit`, `probit`, `tobit`, `poisson`, `nbreg`, `mlogit`, `ologit`, `margins` for nonlinear |
215| `references/bootstrap-simulation.md` | `bootstrap`, `simulate`, `permute`, Monte Carlo |
216| `references/survey-data-analysis.md` | `svyset`, `svy:`, `subpop()`, complex survey design, replicate weights |
217| `references/missing-data-handling.md` | `mi impute`, `mi estimate`, FIML, `misstable`, diagnostics |
218| `references/maximum-likelihood.md` | `ml model`, custom likelihood functions, `ml init`, gradient-based optimization |
219| `references/gmm-estimation.md` | `gmm`, moment conditions, `estat overid`, J-test |
220
221### Causal Inference
222| File | Topics & Key Commands |
223|------|----------------------|
224| `references/treatment-effects.md` | `teffects ra/ipw/ipwra/aipw`, `stteffects`, ATE/ATT/ATET |
225| `references/difference-in-differences.md` | DiD, parallel trends, event studies, staggered adoption |
226| `references/regression-discontinuity.md` | Sharp/fuzzy RD, bandwidth selection, `rdplot` |
227| `references/matching-methods.md` | PSM, nearest neighbor, kernel matching, `teffects nnmatch` |
228| `references/sample-selection.md` | `heckman`, `heckprobit`, treatment models, exclusion restrictions |
229
230### Advanced Methods
231| File | Topics & Key Commands |
232|------|----------------------|
233| `references/survival-analysis.md` | `stset`, `stcox`, `streg`, Kaplan-Meier, parametric models |
234| `references/sem-factor-analysis.md` | `sem`, `gsem`, CFA, path analysis, `alpha`, reliability |
235| `references/nonparametric-methods.md` | `kdensity`, rank tests, `qreg`, `npregress` |
236| `references/spatial-analysis.md` | `spmatrix`, `spregress`, spatial weights, Moran's I |
237| `references/machine-learning.md` | `lasso`, `elasticnet`, `cvlasso`, cross-validation |
238
239### Graphics
240| File | Topics & Key Commands |
241|------|----------------------|
242| `references/graphics.md` | `twoway`, `scatter`, `line`, `bar`, `histogram`, `graph combine`, `graph export`, schemes |
243
244### Programming
245| File | Topics & Key Commands |
246|------|----------------------|
247| `references/programming-basics.md` | `local`, `global`, `foreach`, `forvalues`, `program define`, `syntax`, `return` |
248| `references/advanced-programming.md` | `syntax`, `mata`, classes, `_prefix`, dialog boxes, `tempfile`/`tempvar` |
249| `references/mata-introduction.md` | Mata basics, when to use Mata vs ado, data types |
250| `references/mata-programming.md` | Mata functions, flow control, structures, pointers |
251| `references/mata-matrix-operations.md` | Matrix creation, decompositions, solvers, `st_matrix()` |
252| `references/mata-data-access.md` | `st_data()`, `st_view()`, `st_store()`, performance tips |
253
254### Output & Workflow
255| File | Topics & Key Commands |
256|------|----------------------|
257| `references/tables-reporting.md` | `putexcel`, `putdocx`, `putpdf`, LaTeX integration, `collect` |
258| `references/workflow-best-practices.md` | Project structure, master do-files, version control, debugging, common mistakes |
259| `references/external-tools-integration.md` | Python via `python:`, R via `rsource`, shell commands, Git |
260
261### Community Packages
262| File | What It Does |
263|------|-------------|
264| `packages/reghdfe.md` | High-dimensional fixed effects OLS (absorbs multiple FE sets efficiently) |
265| `packages/estout.md` | `esttab`/`estout`: publication-quality regression tables |
266| `packages/outreg2.md` | Alternative regression table exporter (Word, Excel, TeX) |
267| `packages/asdoc.md` | One-command Word document creation for any Stata output |
268| `packages/tabout.md` | Cross-tabulations and summary tables to file |
269| `packages/coefplot.md` | Coefficient plots from stored estimates |
270| `packages/graph-schemes.md` | `grstyle`, `schemepack`, `plotplain` — better graph themes |
271| `packages/did.md` | Modern DiD: `csdid`, `did_multiplegt`, `did_imputation` (Callaway-Sant'Anna, de Chaisemartin-D'Haultfoeuille, Borusyak-Jaravel-Spiess) |
272| `packages/event-study.md` | `eventstudyinteract`, `eventdd` — event study estimators |
273| `packages/rdrobust.md` | Robust RD estimation with optimal bandwidth (`rdrobust`, `rdplot`, `rdbwselect`) |
274| `packages/psmatch2.md` | Propensity score matching (nearest neighbor, kernel, radius) |
275| `packages/synth.md` | Synthetic control method (`synth`, `synth_runner`) |
276| `packages/ivreg2.md` | Enhanced IV/2SLS: `ivreg2`, `xtivreg2` with additional diagnostics |
277| `packages/xtabond2.md` | Dynamic panel GMM (Arellano-Bond/Blundell-Bond) |
278| `packages/binsreg.md` | Binned scatter plots with CI (`binsreg`, `binstest`) |
279| `packages/nprobust.md` | Nonparametric kernel estimation and inference |
280| `packages/diagnostics.md` | `bacondecomp`, `xttest3`, collinearity, heteroskedasticity tests |
281| `packages/winsor.md` | Winsorizing and trimming: `winsor2`, `winsor` |
282| `packages/data-manipulation.md` | `gtools` (fast collapse/egen), `rangestat`, `egenmore` |
283| `packages/package-management.md` | `ssc install`, `net install`, `ado update`, finding packages |
284
285---
286
287## Common Patterns
288
289### Regression Table Workflow
290```stata
291* Estimate models
292eststo clear
293eststo: regress y x1 x2, vce(robust)
294eststo: regress y x1 x2 x3, vce(robust)
295eststo: regress y x1 x2 x3 x4, vce(cluster id)
296
297* Export table
298esttab using "results.tex", replace ///
299 se star(* 0.10 ** 0.05 *** 0.01) ///
300 label booktabs ///
301 title("Main Results") ///
302 mtitles("(1)" "(2)" "(3)")
303```
304
305### Panel Data Setup
306```stata
307xtset panelid timevar // declare panel structure
308xtdescribe // check balance
309xtsum outcome // within/between variation
310
311* Fixed effects
312xtreg y x1 x2, fe vce(cluster panelid)
313* Or with reghdfe (preferred for multiple FE)
314reghdfe y x1 x2, absorb(panelid timevar) vce(cluster panelid)
315```
316
317### Difference-in-Differences
318```stata
319* Classic 2x2 DiD
320gen post = (year >= treatment_year)
321gen treat_post = treated * post
322regress y treated post treat_post, vce(cluster id)
323
324* Modern staggered DiD (Callaway & Sant'Anna)
325csdid y x1 x2, ivar(id) time(year) gvar(first_treat) agg(event)
326csdid_plot
327```
328
329### Graph Export
330```stata
331* Publication-quality scatter with fit line
332twoway (scatter y x, mcolor(navy%50) msize(small)) ///
333 (lfit y x, lcolor(cranberry) lwidth(medthick)), ///
334 title("Title Here") ///
335 xtitle("X Label") ytitle("Y Label") ///
336 legend(off) scheme(s2color)
337graph export "figure1.pdf", replace as(pdf)
338graph export "figure1.png", replace as(png) width(2400)
339```
340
341### Data Cleaning Pipeline
342```stata
343* Load and inspect
344import delimited "raw_data.csv", clear varnames(1)
345describe
346codebook, compact
347
348* Clean
349rename *, lower // lowercase all varnames
350destring income, replace force // convert string to numeric
351replace income = . if income < 0
352
353* Label
354label variable income "Annual household income (USD)"
355label define yesno 0 "No" 1 "Yes"
356label values employed yesno
357
358* Save
359compress
360save "clean_data.dta", replace
361```
362
363### Multiple Imputation
364```stata
365mi set mlong
366mi register imputed income education
367mi impute chained (regress) income (ologit) education = age i.gender, add(20) rseed(12345)
368mi estimate: regress wage income education age i.gender
369```