Skip to content

brycewang-stanford/Auto-Empirical-Research-Skills / skills/14-luischanci-claude-code-research-starter/dot-claude/skills/stata

Comprehensive Stata reference for writing correct .do files, data management, econometrics, causal inference, graphics, Mata programming, and 17+ 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.

FileKindSize
SKILL.mdskill md13.1 KB
packages/asdoc.mdmarkdown8.5 KB
packages/binsreg.mdmarkdown10.0 KB
packages/coefplot.mdmarkdown9.3 KB
packages/data-manipulation.mdmarkdown10.1 KB
packages/diagnostics.mdmarkdown15.3 KB
packages/did.mdmarkdown15.4 KB
packages/estout.mdmarkdown16.9 KB
packages/event-study.mdmarkdown29.1 KB
packages/graph-schemes.mdmarkdown14.1 KB
packages/ivreg2.mdmarkdown11.1 KB
packages/nprobust.mdmarkdown12.4 KB
packages/outreg2.mdmarkdown11.2 KB
packages/package-management.mdmarkdown10.2 KB
packages/psmatch2.mdmarkdown17.8 KB
packages/rdrobust.mdmarkdown13.4 KB
packages/reghdfe.mdmarkdown10.4 KB
packages/synth.mdmarkdown22.6 KB
packages/tabout.mdmarkdown12.1 KB
packages/winsor.mdmarkdown6.7 KB
packages/xtabond2.mdmarkdown14.9 KB
references/advanced-programming.mdmarkdown10.1 KB
references/basics-getting-started.mdmarkdown5.8 KB
references/bootstrap-simulation.mdmarkdown6.7 KB
references/data-import-export.mdmarkdown7.4 KB
references/data-management.mdmarkdown9.2 KB
references/date-time-functions.mdmarkdown6.8 KB
references/descriptive-statistics.mdmarkdown6.4 KB
references/difference-in-differences.mdmarkdown18.6 KB
references/external-tools-integration.mdmarkdown19.6 KB
references/gmm-estimation.mdmarkdown8.8 KB
references/graphics.mdmarkdown8.2 KB
references/limited-dependent-variables.mdmarkdown7.8 KB
references/linear-regression.mdmarkdown11.0 KB
references/machine-learning.mdmarkdown12.4 KB
references/mata-data-access.mdmarkdown6.8 KB
references/mata-introduction.mdmarkdown6.4 KB
references/mata-matrix-operations.mdmarkdown5.8 KB
references/mata-programming.mdmarkdown8.4 KB
references/matching-methods.mdmarkdown19.2 KB
references/mathematical-functions.mdmarkdown7.0 KB
references/maximum-likelihood.mdmarkdown16.6 KB
references/missing-data-handling.mdmarkdown18.2 KB
references/nonparametric-methods.mdmarkdown11.7 KB
references/panel-data.mdmarkdown7.7 KB
references/programming-basics.mdmarkdown7.9 KB
references/regression-discontinuity.mdmarkdown13.4 KB
references/sample-selection.mdmarkdown17.7 KB
references/sem-factor-analysis.mdmarkdown14.5 KB
references/spatial-analysis.mdmarkdown19.5 KB
references/string-functions.mdmarkdown8.7 KB
references/survey-data-analysis.mdmarkdown12.8 KB
references/survival-analysis.mdmarkdown12.3 KB
references/tables-reporting.mdmarkdown24.1 KB
references/time-series.mdmarkdown7.1 KB
references/treatment-effects.mdmarkdown23.1 KB
references/variables-operators.mdmarkdown4.9 KB
references/workflow-best-practices.mdmarkdown25.2 KB

references/programming-basics.md

View on GitHub
# Stata Programming Basics

## Do-files and Ado-files

### Do-files

```stata
// Running
do "path/to/analysis.do"
quietly do "path/to/analysis.do"

// Best practice template
version 17
clear all
set more off
log using "analysis_log.log", replace

sysuse auto, clear
// ... analysis ...

log close
```

### Ado-files

Ado-files extend Stata's functionality and are auto-loaded when called.

```stata
* mysumm.ado
program define mysumm
    version 17
    syntax varlist [if] [in]
    marksample touse
    foreach var of local varlist {
        quietly summarize `var' if `touse'
        display as text "`var': " as result %9.2f r(mean) ///
            " (SD: " %9.2f r(sd) ")"
    }
end
```

**Where to save:** `adopath` shows directories. Use PLUS directory for user-installed programs.

---

## Local and Global Macros

### Local Macros

Exist only within the current program or do-file. Referenced with backtick-quote: `` `name' ``.

```stata
local filename "mydata.dta"
use "`filename'", clear

local n = 100
display "Sample size: `n'"

local demog_vars "age gender education income"
summarize `demog_vars'
```

**Extended macro functions:**

```stata
local price_label : variable label price
local foreign_vallabel : value label foreign
local count : word count `mylist'
local third : word 3 of `mylist'
```

### Global Macros

Persist throughout the session. Referenced with `$name`.

```stata
global datadir "/home/user/data"
use "$datadir/myfile.dta", clear

global controls "age gender education income"
regress outcome treatment $controls
```

**Caution:** Globals create conflicts across programs. Prefer locals. Clear when done: `macro drop _all`.

---

## Loops

### foreach Loop

```stata
// Over variable names
foreach var of varlist price mpg weight {
    quietly summarize `var'
    display "`var': mean = " r(mean)
}

// Over strings
foreach country in "USA" "Canada" "Mexico" {
    count if country == "`country'"
}

// Over a local macro
local outcomes "income health education"
foreach outcome of local outcomes {
    regress `outcome' `controls'
    estimates store model_`outcome'
}

// Over all numeric variables
foreach var of varlist _all {
    capture confirm numeric variable `var'
    if !_rc {
        summarize `var'
    }
}

// Nested loops
foreach year of local years {
    foreach region of local regions {
        // ...
    }
}
```

### forvalues Loop

```stata
forvalues i = 1/10 {
    display "Iteration `i'"
}

forvalues year = 2000(5)2020 {
    display "Year: `year'"
}

forvalues i = 1/5 {
    generate category`i' = (category == `i')
}
```

---

## Conditional Statements

```stata
// Basic if
if _N > 50 {
    display "Large dataset"
}

// if/else
capture confirm variable price
if !_rc {
    summarize price
}
else {
    display "Variable 'price' not found"
}

// if/else if/else
if `age' < 18 {
    local category "Minor"
}
else if `age' >= 18 & `age' < 65 {
    local category "Adult"
}
else {
    local category "Senior"
}

// capture for error handling
capture drop newvar
generate newvar = oldvar * 2

capture confirm file "mydata.dta"
if _rc == 0 {
    use mydata.dta, clear
}
else {
    display "File not found"
}
```

---

## Programs and Functions

### Basic Structure

```stata
program define programname
    version 17
    syntax [varlist] [if] [in] [, options]
    // Program code
end
```

### Program with syntax

```stata
program define myreg
    version 17
    syntax varlist(min=2) [if] [in] [, Robust CLuster(varname)]

    local depvar : word 1 of `varlist'
    local indepvars : list varlist - depvar

    if "`robust'" != "" {
        regress `depvar' `indepvars' `if' `in', robust
    }
    else if "`cluster'" != "" {
        regress `depvar' `indepvars' `if' `in', cluster(`cluster')
    }
    else {
        regress `depvar' `indepvars' `if' `in'
    }
end

myreg price mpg weight, robust
```

### Ado-file with Return Values

```stata
*! version 1.0.0
program define mystats, rclass
    version 17
    syntax varname [if] [in] [, Detail]
    marksample touse

    quietly summarize `varlist' if `touse', detail

    return scalar N = r(N)
    return scalar mean = r(mean)
    return scalar sd = r(sd)

    if "`detail'" != "" {
        return scalar p50 = r(p50)
    }

    display as text "Variable: " as result "`varlist'"
    display as text "Mean: " as result %9.2f return(mean)
end
```

---

## return and ereturn

### r-class (general results)

```stata
program define compute_stats, rclass
    syntax varname
    quietly summarize `varlist'
    return scalar mean = r(mean)
    return scalar cv = r(sd) / r(mean)
    return local varname "`varlist'"
end

compute_stats price
display "CV: " r(cv)
```

**Gotcha:** r-class results are overwritten by the next r-class command. Save to locals immediately.

### e-class (estimation results)

```stata
program define myregress, eclass
    syntax varlist [if] [in]
    marksample touse
    local depvar : word 1 of `varlist'
    local indepvars : list varlist - depvar
    regress `depvar' `indepvars' if `touse'
    ereturn local cmd "myregress"
    ereturn local depvar "`depvar'"
end
```

**Key difference:** e-class results persist until the next estimation command, even through r-class calls.

### Returning Matrices

```stata
program define return_matrix, rclass
    matrix A = (1, 2, 3 \ 4, 5, 6)
    return matrix mymatrix = A
end
```

---

## preserve and restore

```stata
preserve
collapse (mean) avg_price=price, by(foreign)
list
restore
// Original data unchanged

// In loops
foreach condition of local groups {
    preserve
    keep if `condition'
    summarize price mpg weight
    restore
}

// Nested
preserve
    drop if missing(rep78)
    preserve
        collapse (mean) price, by(foreign)
        list
    restore
    // Back to non-missing rep78 data
restore
// Back to original
```

---

## quietly and noisily

```stata
// Suppress output
quietly summarize price
display "Mean: " r(mean)

// Block suppression
quietly {
    use mydata, clear
    generate newvar = oldvar * 2
    summarize newvar
}

// Force display inside quiet block
quietly {
    noisily summarize newvar
    regress y x
}

// In loops (faster)
foreach var of varlist price mpg weight {
    quietly summarize `var'
    display "`var': mean = " %9.2f r(mean)
}

// Suppress errors
capture quietly {
    use nonexistent_file.dta
}
if _rc {
    display "Error occurred"
}
```

---

## Reusable Code Patterns

### Data Cleaning Program

```stata
program define clean_data, rclass
    version 17
    syntax [, Outliers(real 3)]
    local n_original = _N
    quietly {
        foreach var of varlist _all {
            capture confirm numeric variable `var'
            if !_rc {
                summarize `var', detail
                drop if abs(`var' - r(mean)) > `outliers' * r(sd)
            }
        }
    }
    local n_dropped = `n_original' - _N
    return scalar n_dropped = `n_dropped'
    display as text "Dropped: " as result `n_dropped'
end
```

### Data Validation

```stata
program define validate_data
    version 17
    syntax [, REQuired(varlist) POSitive(varlist) UNIque(varlist)]
    local errors = 0

    if "`required'" != "" {
        foreach var of local required {
            capture confirm variable `var'
            if _rc {
                display as error "Required variable `var' not found"
                local ++errors
            }
            else {
                count if missing(`var')
                if r(N) > 0 {
                    display as error "`var' has " r(N) " missing values"
                    local ++errors
                }
            }
        }
    }

    if `errors' == 0 {
        display as result "All checks passed"
    }
    else {
        display as error "`errors' error(s)"
        exit 198
    }
end
```

### Best Practices

1. **Version control:** `version 17`
2. **Document:** `*! version 1.0.0  Author`
3. **Validate inputs:** `marksample touse` + `count if `touse''`
4. **Return results:** `program define ..., rclass`
5. **Handle errors:** `capture confirm file ...`
6. **Modular design:** Separate programs for load, clean, analyze
finishing-a-development-branchobra/superpowersUse when implementation is complete, all tests pass, and you need to decide how to integrate the workStars: 322kUpdated Claude CodeCodexVerifiedInstall
systematic-debuggingobra/superpowersUse when encountering any bug, test failure, or unexpected behavior, before proposing fixesStars: 322kUpdated Claude CodeCodexVerifiedInstall
test-driven-developmentobra/superpowersUse when implementing any feature or bugfix, before writing implementation codeStars: 322kUpdated Claude CodeCodexVerifiedInstall
skill-creatoranthropics/skillsCreate new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an existing skill, run evals to test a skill, benchmark skill performance with variance analysis, or optimize a skill's description for better triggering accuracy.Stars: 198kUpdated Claude CodeCodexVerifiedInstall