Stata Skill
Use this skill whenever writing, editing, running, or debugging Stata .do files,
or when you need to look up Stata syntax, commands, or options.
1. What is Stata
Stata is a statistical software package for data management, analysis, and graphics.
It is widely used in economics, political science, epidemiology, and other social sciences.
Key concepts:
.do files: Scripts (plain text) containing Stata commands, executed sequentially.
.dta files: Stata's binary data format.
.log files: Text output captured during a Stata session or batch run.
ado files: Stata programs (user-written or official) that extend functionality.
- Macros:
local (temporary) and global (persistent within session) named values.
- Factor variables:
i.varname notation for categorical regressors.
- Postestimation: Commands run after a model fit (e.g.,
predict, margins, estat).
2. Running Stata in This Environment
Finding the installation: Stata is installed in C:\Program Files\ on Windows.
To auto-detect the path:
STATA_DIR=$(ls -d "/c/Program Files"/Stata* "/c/Program Files"/StataNow* 2>/dev/null | sort -V | tail -1)
echo "$STATA_DIR"
From bash (Claude Code terminal):
stata -b do path/to/script.do # batch mode, creates .log file
stata path/to/script.do # interactive window
IMPORTANT: ALWAYS use the stata wrapper command (at ~/bin/stata), NEVER call
StataSE-64.exe directly. The wrapper auto-moves batch-mode logs from the current
directory to quality_reports/stata_logs/. Calling the exe directly leaves stray
.log files in the project root.
From PowerShell (user terminal):
stata -b do path\to\script.do
The stata alias must point to StataSE-64.exe (or StataMP-64.exe depending on
edition). See SETUP.md for how to configure this.
Checking for errors after batch run:
grep "^r(" script.log # Stata error codes start with r(
If the log contains r( lines, the script hit an error at that point.
3. Writing .do Files — Essentials
File structure
version 17
clear all
set more off
* --- 0. Paths ---
do config_local.do // sets $root
* --- 1. Load data ---
use "$root/data/processed/tweets_processed.dta", clear
* --- 2. Analysis ---
reg vote_share engagement_score, robust
* --- 3. Output ---
esttab using "$root/output/tables/table1.tex", booktabs label replace
graph export "$root/output/figures/fig1.png", replace width(2400)
Key patterns
version 17 at top for reproducibility
- All paths via
$root global macro (set in config_local.do)
clear all / set more off at the start
replace on all output commands (allows re-running)
width(2400) for ~300 DPI figures at 8 inches
graphregion(color(white)) bgcolor(white) for white backgrounds
- Line continuation with
///
Common pitfalls
encode assigns codes alphabetically — verify ordering before interpreting
sort is not stable — add enough keys to uniquely identify rows
- Use
vce(cluster var) not just robust when observations are grouped
destring for numeric-as-string; encode for true categoricals — never confuse them
4. Stata PDF Documentation
Location
Stata bundles its full documentation as PDFs inside the installation directory:
<STATA_INSTALL_DIR>/docs/
To find the docs directory automatically:
STATA_DOCS=$(ls -d "/c/Program Files"/Stata*/docs "/c/Program Files"/StataNow*/docs 2>/dev/null | sort -V | tail -1)
echo "$STATA_DOCS"
Complete manual index (37 PDFs, ~17,000 total pages)
| File |
Manual |
Pages |
Key contents |
r.pdf |
Base Reference |
3,502 |
regress, logit, probit, test, predict, margins — the most-used manual |
u.pdf |
User's Guide |
403 |
Stata basics, syntax, data types, programming intro |
d.pdf |
Data Management |
1,000 |
import, merge, reshape, append, encode, destring |
ts.pdf |
Time Series |
1,026 |
arima, var, vec, irf, tsset |
xt.pdf |
Panel Data |
699 |
xtreg, xtlogit, xtpoisson, xtset |
me.pdf |
Mixed Effects |
572 |
mixed, melogit, mepoisson |
st.pdf |
Survival Analysis |
645 |
stset, stcox, streg, sts |
mv.pdf |
Multivariate |
750 |
factor, pca, cluster, manova |
sem.pdf |
SEM |
680 |
sem, gsem, path diagrams |
g.pdf |
Graphics |
799 |
twoway, graph bar, scheme, options |
p.pdf |
Programming |
667 |
program, macro, mata interface |
m.pdf |
Mata |
1,214 |
Stata's matrix programming language |
bayes.pdf |
Bayesian |
911 |
bayesmh, bayesian estimation |
causal.pdf |
Causal Inference |
746 |
teffects, didregress, stteffects |
lasso.pdf |
Lasso |
394 |
lasso, elasticnet, cross-validation |
mi.pdf |
Multiple Imputation |
400 |
mi impute, mi estimate |
svy.pdf |
Survey |
236 |
svyset, svy: prefix |
tables.pdf |
Tables |
361 |
collect, table, dtable, etable |
pss.pdf |
Power/Sample Size |
869 |
power, sample size calculations |
meta.pdf |
Meta-Analysis |
439 |
meta set, meta forestplot |
fn.pdf |
Functions |
193 |
Built-in functions reference |
i.pdf |
Glossary/Index |
328 |
Combined subject index |
stoc.pdf |
Subject TOC |
59 |
Combined table of contents across all manuals |
adapt.pdf |
Adaptive Designs |
252 |
Group sequential trials |
bma.pdf |
Bayesian Model Averaging |
241 |
bmaregress, model selection |
cm.pdf |
Choice Models |
329 |
cmclogit, conditional logit, mixed logit |
dsge.pdf |
DSGE Models |
179 |
Dynamic stochastic general equilibrium |
erm.pdf |
Extended Regression |
307 |
Extended regression models (endogeneity, selection, treatment) |
fmm.pdf |
Finite Mixture Models |
149 |
fmm prefix, latent class |
gsm.pdf |
Getting Started (Mac) |
158 |
Mac-specific setup guide |
gsu.pdf |
Getting Started (Unix) |
165 |
Unix-specific setup guide |
gsw.pdf |
Getting Started (Windows) |
161 |
Windows-specific setup guide |
h2oml.pdf |
H2O Machine Learning |
379 |
h2oml, random forest, gradient boosting |
ig.pdf |
Installation Guide |
21 |
License, installation |
irt.pdf |
Item Response Theory |
251 |
irt, Rasch, 2PL, 3PL models |
rpt.pdf |
Reporting |
222 |
putdocx, putpdf, collect, automated reports |
sp.pdf |
Spatial |
232 |
spregress, spatial autoregressive models |
Start with stoc.pdf (59 pages) to find which manual covers a topic.
5. Reading Documentation Efficiently (Token-Saving Strategies)
Problem: 17,000 pages of PDFs. Reading even one manual wastes tokens.
Solution: Use targeted extraction — never read a full manual.
Prerequisites: pdftotext (bundled with poppler/mingw) and pip install pdfplumber.
See SETUP.md for installation.
Tool 1: pdftotext (fast, plain text, best for prose)
# Auto-detect docs path
STATA_DOCS=$(ls -d "/c/Program Files"/Stata*/docs "/c/Program Files"/StataNow*/docs 2>/dev/null | sort -V | tail -1)
# Extract specific pages (e.g., pages 1200-1220 for regress)
pdftotext -f 1200 -l 1220 "$STATA_DOCS/r.pdf" -
# Search the subject TOC for a command
pdftotext "$STATA_DOCS/stoc.pdf" - | grep -i "regress"
Tool 2: pdfplumber (Python, best for tables and structured content)
import pdfplumber, glob, os
def find_stata_docs():
"""Auto-detect Stata docs directory."""
for pattern in [r"C:\Program Files\StataNow*\docs",
r"C:\Program Files\Stata*\docs"]:
matches = glob.glob(pattern)
if matches:
return sorted(matches)[-1]
return None
def stata_doc_lookup(manual: str, start_page: int, end_page: int) -> str:
"""Extract text from a Stata manual. Pages are 0-indexed."""
docs = find_stata_docs()
path = os.path.join(docs, manual)
with pdfplumber.open(path) as pdf:
text = []
for i in range(start_page, min(end_page, len(pdf.pages))):
page_text = pdf.pages[i].extract_text()
if page_text:
text.append(page_text)
return "\n".join(text)
# Example: read TOC of r.pdf to find page numbers
print(stata_doc_lookup("r.pdf", 2, 8))
Tool 3: pdftotext + grep (search without reading)
STATA_DOCS=$(ls -d "/c/Program Files"/Stata*/docs "/c/Program Files"/StataNow*/docs 2>/dev/null | sort -V | tail -1)
# Find which page mentions "margins" in the base reference
pdftotext "$STATA_DOCS/r.pdf" - | grep -n "margins"
# Find a command across ALL manuals
for f in "$STATA_DOCS"/*.pdf; do
if pdftotext "$f" - 2>/dev/null | grep -q "didregress"; then
echo "Found in: $(basename $f)"
fi
done
Recommended lookup workflow
- Start with
stoc.pdf — search the subject TOC to identify which manual
- Read the manual's own TOC (pages 2-8) to find the exact page range
- Extract only those pages with
pdftotext -f START -l END manual.pdf -
- Never extract more than 20 pages at once — if you need more, narrow the search
Token cost estimates
- 1 PDF page ~ 500-800 tokens
- Full
r.pdf ~ 2.1M tokens (NEVER do this)
stoc.pdf (59 pages) ~ 35K tokens (acceptable for initial lookup)
- Targeted 10-page extract ~ 6K tokens (ideal)
6. Quick Reference: Common Tasks
| Task |
Where to look |
| Regression syntax |
r.pdf, search TOC for "regress" |
| Merge datasets |
d.pdf, search for "merge" |
| Panel data models |
xt.pdf, search for "xtreg" |
| Export LaTeX tables |
r.pdf search "esttab" or tables.pdf |
| Graph options |
g.pdf TOC |
| String functions |
fn.pdf or d.pdf search "string functions" |
| Date/time handling |
d.pdf or u.pdf chapter on dates |
| Causal inference |
causal.pdf TOC |
| Survey weights |
svy.pdf TOC |
1---2name: stata-23description: Context and tools for working with Stata — writing .do files, running them in batch mode, and efficiently consulting the bundled PDF documentation.4---5
6# Stata Skill
7
8Use this skill whenever writing, editing, running, or debugging Stata `.do` files,
9or when you need to look up Stata syntax, commands, or options.
10
11---
12
13## 1. What is Stata
14
15Stata is a statistical software package for data management, analysis, and graphics.
16It is widely used in economics, political science, epidemiology, and other social sciences.
17
18Key concepts:
19- **`.do` files**: Scripts (plain text) containing Stata commands, executed sequentially.
20- **`.dta` files**: Stata's binary data format.
21- **`.log` files**: Text output captured during a Stata session or batch run.
22- **`ado` files**: Stata programs (user-written or official) that extend functionality.
23- **Macros**: `local` (temporary) and `global` (persistent within session) named values.
24- **Factor variables**: `i.varname` notation for categorical regressors.
25- **Postestimation**: Commands run after a model fit (e.g., `predict`, `margins`, `estat`).
26
27---
28
29## 2. Running Stata in This Environment
30
31**Finding the installation:** Stata is installed in `C:\Program Files\` on Windows.
32To auto-detect the path:
33```bash
34STATA_DIR=$(ls -d "/c/Program Files"/Stata* "/c/Program Files"/StataNow* 2>/dev/null | sort -V | tail -1)
35echo "$STATA_DIR"
36```
37
38**From bash (Claude Code terminal):**
39```bash
40stata -b do path/to/script.do # batch mode, creates .log file
41stata path/to/script.do # interactive window
42```
43
44**IMPORTANT:** ALWAYS use the `stata` wrapper command (at `~/bin/stata`), NEVER call
45`StataSE-64.exe` directly. The wrapper auto-moves batch-mode logs from the current
46directory to `quality_reports/stata_logs/`. Calling the exe directly leaves stray
47`.log` files in the project root.
48
49**From PowerShell (user terminal):**
50```powershell
51stata -b do path\to\script.do
52```
53
54The `stata` alias must point to `StataSE-64.exe` (or `StataMP-64.exe` depending on
55edition). See `SETUP.md` for how to configure this.
56
57**Checking for errors after batch run:**
58```bash
59grep "^r(" script.log # Stata error codes start with r(
60```
61If the log contains `r(` lines, the script hit an error at that point.
62
63---
64
65## 3. Writing `.do` Files — Essentials
66
67### File structure
68```stata
69version 17
70clear all
71set more off
72
73* --- 0. Paths ---
74do config_local.do // sets $root
75
76* --- 1. Load data ---
77use "$root/data/processed/tweets_processed.dta", clear
78
79* --- 2. Analysis ---
80reg vote_share engagement_score, robust
81
82* --- 3. Output ---
83esttab using "$root/output/tables/table1.tex", booktabs label replace
84graph export "$root/output/figures/fig1.png", replace width(2400)
85```
86
87### Key patterns
88- `version 17` at top for reproducibility
89- All paths via `$root` global macro (set in `config_local.do`)
90- `clear all` / `set more off` at the start
91- `replace` on all output commands (allows re-running)
92- `width(2400)` for ~300 DPI figures at 8 inches
93- `graphregion(color(white)) bgcolor(white)` for white backgrounds
94- Line continuation with `///`
95
96### Common pitfalls
97- `encode` assigns codes alphabetically — verify ordering before interpreting
98- `sort` is not stable — add enough keys to uniquely identify rows
99- Use `vce(cluster var)` not just `robust` when observations are grouped
100- `destring` for numeric-as-string; `encode` for true categoricals — never confuse them
101
102---
103
104## 4. Stata PDF Documentation
105
106### Location
107Stata bundles its full documentation as PDFs inside the installation directory:
108```
109<STATA_INSTALL_DIR>/docs/
110```
111
112To find the docs directory automatically:
113```bash
114STATA_DOCS=$(ls -d "/c/Program Files"/Stata*/docs "/c/Program Files"/StataNow*/docs 2>/dev/null | sort -V | tail -1)
115echo "$STATA_DOCS"
116```
117
118### Complete manual index (37 PDFs, ~17,000 total pages)
119
120| File | Manual | Pages | Key contents |
121|------|--------|-------|--------------|
122| `r.pdf` | **Base Reference** | 3,502 | regress, logit, probit, test, predict, margins — the most-used manual |
123| `u.pdf` | **User's Guide** | 403 | Stata basics, syntax, data types, programming intro |
124| `d.pdf` | **Data Management** | 1,000 | import, merge, reshape, append, encode, destring |
125| `ts.pdf` | **Time Series** | 1,026 | arima, var, vec, irf, tsset |
126| `xt.pdf` | **Panel Data** | 699 | xtreg, xtlogit, xtpoisson, xtset |
127| `me.pdf` | **Mixed Effects** | 572 | mixed, melogit, mepoisson |
128| `st.pdf` | **Survival Analysis** | 645 | stset, stcox, streg, sts |
129| `mv.pdf` | **Multivariate** | 750 | factor, pca, cluster, manova |
130| `sem.pdf` | **SEM** | 680 | sem, gsem, path diagrams |
131| `g.pdf` | **Graphics** | 799 | twoway, graph bar, scheme, options |
132| `p.pdf` | **Programming** | 667 | program, macro, mata interface |
133| `m.pdf` | **Mata** | 1,214 | Stata's matrix programming language |
134| `bayes.pdf` | **Bayesian** | 911 | bayesmh, bayesian estimation |
135| `causal.pdf` | **Causal Inference** | 746 | teffects, didregress, stteffects |
136| `lasso.pdf` | **Lasso** | 394 | lasso, elasticnet, cross-validation |
137| `mi.pdf` | **Multiple Imputation** | 400 | mi impute, mi estimate |
138| `svy.pdf` | **Survey** | 236 | svyset, svy: prefix |
139| `tables.pdf` | **Tables** | 361 | collect, table, dtable, etable |
140| `pss.pdf` | **Power/Sample Size** | 869 | power, sample size calculations |
141| `meta.pdf` | **Meta-Analysis** | 439 | meta set, meta forestplot |
142| `fn.pdf` | **Functions** | 193 | Built-in functions reference |
143| `i.pdf` | **Glossary/Index** | 328 | Combined subject index |
144| `stoc.pdf` | **Subject TOC** | 59 | Combined table of contents across all manuals |
145| `adapt.pdf` | **Adaptive Designs** | 252 | Group sequential trials |
146| `bma.pdf` | **Bayesian Model Averaging** | 241 | bmaregress, model selection |
147| `cm.pdf` | **Choice Models** | 329 | cmclogit, conditional logit, mixed logit |
148| `dsge.pdf` | **DSGE Models** | 179 | Dynamic stochastic general equilibrium |
149| `erm.pdf` | **Extended Regression** | 307 | Extended regression models (endogeneity, selection, treatment) |
150| `fmm.pdf` | **Finite Mixture Models** | 149 | fmm prefix, latent class |
151| `gsm.pdf` | **Getting Started (Mac)** | 158 | Mac-specific setup guide |
152| `gsu.pdf` | **Getting Started (Unix)** | 165 | Unix-specific setup guide |
153| `gsw.pdf` | **Getting Started (Windows)** | 161 | Windows-specific setup guide |
154| `h2oml.pdf` | **H2O Machine Learning** | 379 | h2oml, random forest, gradient boosting |
155| `ig.pdf` | **Installation Guide** | 21 | License, installation |
156| `irt.pdf` | **Item Response Theory** | 251 | irt, Rasch, 2PL, 3PL models |
157| `rpt.pdf` | **Reporting** | 222 | putdocx, putpdf, collect, automated reports |
158| `sp.pdf` | **Spatial** | 232 | spregress, spatial autoregressive models |
159
160**Start with `stoc.pdf`** (59 pages) to find which manual covers a topic.
161
162---
163
164## 5. Reading Documentation Efficiently (Token-Saving Strategies)
165
166**Problem:** 17,000 pages of PDFs. Reading even one manual wastes tokens.
167**Solution:** Use targeted extraction — never read a full manual.
168
169**Prerequisites:** `pdftotext` (bundled with poppler/mingw) and `pip install pdfplumber`.
170See `SETUP.md` for installation.
171
172### Tool 1: `pdftotext` (fast, plain text, best for prose)
173```bash
174# Auto-detect docs path
175STATA_DOCS=$(ls -d "/c/Program Files"/Stata*/docs "/c/Program Files"/StataNow*/docs 2>/dev/null | sort -V | tail -1)
176
177# Extract specific pages (e.g., pages 1200-1220 for regress)
178pdftotext -f 1200 -l 1220 "$STATA_DOCS/r.pdf" -
179
180# Search the subject TOC for a command
181pdftotext "$STATA_DOCS/stoc.pdf" - | grep -i "regress"
182```
183
184### Tool 2: `pdfplumber` (Python, best for tables and structured content)
185```python
186import pdfplumber, glob, os
187
188def find_stata_docs():
189 """Auto-detect Stata docs directory."""
190 for pattern in [r"C:\Program Files\StataNow*\docs",
191 r"C:\Program Files\Stata*\docs"]:
192 matches = glob.glob(pattern)
193 if matches:
194 return sorted(matches)[-1]
195 return None
196
197def stata_doc_lookup(manual: str, start_page: int, end_page: int) -> str:
198 """Extract text from a Stata manual. Pages are 0-indexed."""
199 docs = find_stata_docs()
200 path = os.path.join(docs, manual)
201 with pdfplumber.open(path) as pdf:
202 text = []
203 for i in range(start_page, min(end_page, len(pdf.pages))):
204 page_text = pdf.pages[i].extract_text()
205 if page_text:
206 text.append(page_text)
207 return "\n".join(text)
208
209# Example: read TOC of r.pdf to find page numbers
210print(stata_doc_lookup("r.pdf", 2, 8))
211```
212
213### Tool 3: `pdftotext` + `grep` (search without reading)
214```bash
215STATA_DOCS=$(ls -d "/c/Program Files"/Stata*/docs "/c/Program Files"/StataNow*/docs 2>/dev/null | sort -V | tail -1)
216
217# Find which page mentions "margins" in the base reference
218pdftotext "$STATA_DOCS/r.pdf" - | grep -n "margins"
219
220# Find a command across ALL manuals
221for f in "$STATA_DOCS"/*.pdf; do
222 if pdftotext "$f" - 2>/dev/null | grep -q "didregress"; then
223 echo "Found in: $(basename $f)"
224 fi
225done
226```
227
228### Recommended lookup workflow
2291. **Start with `stoc.pdf`** — search the subject TOC to identify which manual
2302. **Read the manual's own TOC** (pages 2-8) to find the exact page range
2313. **Extract only those pages** with `pdftotext -f START -l END manual.pdf -`
2324. **Never extract more than 20 pages at once** — if you need more, narrow the search
233
234### Token cost estimates
235- 1 PDF page ~ 500-800 tokens
236- Full `r.pdf` ~ 2.1M tokens (NEVER do this)
237- `stoc.pdf` (59 pages) ~ 35K tokens (acceptable for initial lookup)
238- Targeted 10-page extract ~ 6K tokens (ideal)
239
240---
241
242## 6. Quick Reference: Common Tasks
243
244| Task | Where to look |
245|------|--------------|
246| Regression syntax | `r.pdf`, search TOC for "regress" |
247| Merge datasets | `d.pdf`, search for "merge" |
248| Panel data models | `xt.pdf`, search for "xtreg" |
249| Export LaTeX tables | `r.pdf` search "esttab" or `tables.pdf` |
250| Graph options | `g.pdf` TOC |
251| String functions | `fn.pdf` or `d.pdf` search "string functions" |
252| Date/time handling | `d.pdf` or `u.pdf` chapter on dates |
253| Causal inference | `causal.pdf` TOC |
254| Survey weights | `svy.pdf` TOC |