Skip to content
Automation
Skill

/stata

Comprehensive Stata reference for writing correct .do files, data management, econometrics, causal inference, graphics, Mata programming, and 20 community packages (reghdfe, estout, did, rdrobust, etc.). Covers syntax, options, gotchas, and idiomatic patterns. Use this skill

From plugin
auto-empirical-research-skills
4.9k200 skills

Claude Code

$ npx -y skills add brycewang-stanford/Auto-Empirical-Research-Skills --skill stata --agent claude-code

SKILL.md

stata.SKILL.md
name: stata
description: >
  Comprehensive Stata reference for writing correct .do files, data management,
  econometrics, causal inference, graphics, Mata programming, and 20 community
  packages (reghdfe, estout, did, rdrobust, etc.). Covers syntax, options,
  gotchas, and idiomatic patterns. Use this skill whenever the user asks you to
  write, debug, or explain Stata code.

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`

Never skip `tab _merge` — it costs nothing and is the only diagnostic you get when `assert` fails.

merge 1:1 id using other.dta
tab _merge                      // ALWAYS tab before assert
assert _merge == 3              // fails silently without tab output
drop _merge

`preserve` / `restore` + `tempfile` for Collapse-Merge-Back

The standard pattern for computing group stats and merging them onto the original data:

tempfile stats
preserve
collapse (mean) avg_x=x, by(group)
save `stats'
restore
merge m:1 group using `stats'
tab _merge
assert _merge == 3
drop _merge

For simple group means, `bysort group: egen avg_x = mean(x)` avoids the round-trip entirely.

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

---

Running Stata from the Command Line

Claude can execute Stata code by running `.do` files in batch mode from the terminal. This is how to run Stata non-interactively.

Finding the Stata Binary

Stata on macOS is a `.app` bundle. The actual binary is inside it. Common locations:

# Stata 18 / StataNow (most common)
/Applications/Stata/StataMP.app/Contents/MacOS/stata-mp
/Applications/StataNow/StataMP.app/Contents/MacOS/stata-mp

# Other editions (SE, BE)
/Applications/Stata/StataSE.app/Contents/MacOS/stata-se
/Applications/Stata/StataBE.app/Contents/MacOS/stata-be

If Stata isn't on `$PATH`, find it with: `mdfind -name "stata-mp" | grep MacOS`

Batch Mode (`-b`)

# Run a .do file in batch mode — output goes to <filename>.log
/Applications/Stata/StataMP.app/Contents/MacOS/stata-mp -b do analysis.do

# If stata-mp is on PATH (e.g., via symlink or alias):
stata-mp -b do analysis.do
  • `-b` = batch mode (non-interactive, no GUI)
  • Output (everything Stata would display) is written to `analysis.log` in the working directory
  • Exit code is 0 on success, non-zero on error
  • The log file contains all output, including error messages — check it after execution

Running Inline Stata Code

To run a quick Stata snippet without creating a `.do` file:

# Write a temp .do file and run it
cat > /tmp/stata_run.do << 'EOF'
sysuse auto, clear
summarize price mpg
EOF
stata-mp -b do /tmp/stata_run.do
cat /tmp/stata_run.log

Checking Results

# Check if it succeeded
stata-mp -b do tests/run_tests.do && echo "SUCCESS" || echo "FAILED"

# Search
Read more
@brycewang-stanford
Ships withauto-empirical-research-skills

## 🔥 力荐 · StatsPAI — Stata 与 R 的 Python 平替,为 AI Agent 而生 🔁 Stata / R 平替:reghdfe、csdid、rdrobust、synth、fixest、did 等常用命令在 Python 中一站式替代,一个 import statspai as sp 搞定 DID / RD / IV / SCM / DML / matching 🤖 面向 Agent 设计:结构化结果对象 + 内置 MCP Server,Claude / Codex

4.9k200 skills
Get the whole plugin

Stars on GitHub

Momentum

stars in total
4.9k
Star history of brycewang-stanford/Auto-Empirical-Research-Skills on GitHub, a chart by star-history.com

More skills from other plugins.

agent-builder

agent-builder

Load immediately after an Agent intent, before the first agent_builder_* call. Governs how you create, configure, test, and…

n8n2w209k
@n8n-io@n8n-ioInstall Skill
browser-use

browser-use

Direct browser control via CDP for web interaction: automation, scraping, testing, screenshots, and site/app work. Also covers…

@browser-use@browser-useInstall Skill
agent-browser

agent-browser

Browser automation CLI for AI agents. Use when the user needs to interact with websites, including navigating pages, filling…

@vercel-labs-2@vercel-labs-2Install Skill
add-anydoc

add-anydoc

Add local office-document-to-Markdown conversion to NanoClaw agent containers with the pinned Firecrawl AnyDoc CLI. Use when…

@nanocoai@nanocoaiInstall Skill

Questions about stata.

Which coding agents can use stata?
stata installs in Claude Code, Codex, Cursor, Gemini CLI, GitHub Copilot, OpenCode and Windsurf with the skills CLI, using each agent's flag shown on this page. Flowy's auto-invocation, which fires a skill when your prompt matches, runs in Claude Code only.