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/variables-operators.md

View on GitHub
# Variables and Operators in Stata

## Variable Types

### Numeric Variables

| Storage Type | Bytes | Range | Description |
|-------------|-------|-------|-------------|
| `byte` | 1 | -127 to 100 | Small integers |
| `int` | 2 | -32,767 to 32,740 | Medium integers |
| `long` | 4 | -2,147,483,647 to 2,147,483,620 | Large integers |
| `float` | 4 | +/-1.7e+38 | Floating point (default) |
| `double` | 8 | +/-8.9e+307 | High precision floating point |

Only `float` and `double` can hold decimals.

```stata
describe          // View current variable types
recast byte age   // Change storage type
recast double price
```

### String Variables

- `str1` to `str2045`: Fixed-length strings (Stata 13+)
- `strL`: Variable-length strings (up to 2 billion characters)

```stata
gen str20 name = "John Doe"
recast strL description
```

**Best Practice:** Categorical variables should be stored as numeric with value labels, not strings.

### Date and Time Variables

Stored as numbers representing units since January 1, 1960:

| Type | Format | Unit |
|------|--------|------|
| Daily | `%td` | Days |
| Weekly | `%tw` | Weeks |
| Monthly | `%tm` | Months |
| Quarterly | `%tq` | Quarters |
| Yearly | `%ty` | Years |
| Datetime | `%tc` | Milliseconds |

```stata
gen date_var = date(string_date, "DMY")
format date_var %td

gen year = year(date_var)
gen month = month(date_var)

gen double datetime_var = clock(string_datetime, "DMYhms")
format datetime_var %tc
```

## Variable Naming Rules

- Up to 32 characters
- Must start with letter or underscore
- Letters, numbers, underscores only
- **Case-sensitive**: `Age` and `age` are different
- Cannot use reserved words (`if`, `in`, `using`)
- Use lowercase with underscores for readability

## Operators

### Arithmetic
| Operator | Description |
|----------|-------------|
| `+`, `-`, `*`, `/` | Basic arithmetic |
| `^` | Exponentiation |
| `-` (prefix) | Negation |

### Relational
| Operator | Description |
|----------|-------------|
| `==` | Equal to |
| `!=` or `~=` | Not equal to |
| `>`, `>=`, `<`, `<=` | Comparisons |

Returns 1 if true, 0 if false.

### Logical
| Operator | Description |
|----------|-------------|
| `&` | AND |
| `|` | OR |
| `!` or `~` | NOT |

### Operator Precedence (highest to lowest)
1. Parentheses `( )`
2. Negation: `-`, `!`, `~`
3. `^`
4. `*`, `/`
5. `+`, `-`
6. Relational: `>`, `>=`, `<`, `<=`, `==`, `!=`
7. `&`
8. `|`

**Key:** `&` binds tighter than `|`. Use parentheses for clarity:
```stata
gen flag = (age > 18 & income > 50000) | (student == 1)
```

### String Operator
`+` concatenates strings: `gen fullname = firstname + " " + lastname`

## Missing Values

Stata has 27 missing values: `.`, `.a` through `.z`

### Critical: Missing as Positive Infinity

**Missing values are treated as larger than any number.** This affects conditional statements:

```stata
// WRONG - includes missing values!
list if age > 60

// CORRECT
list if age > 60 & !missing(age)
// or
list if age > 60 & age < .
```

### Common Patterns
```stata
misstable summarize              // Overview of missing data
misstable patterns               // Missing patterns
count if missing(age)

replace income = . if income == 999 | income == -99
mvdecode _all, mv(999=. \ -99=.)    // Batch recode to missing

// Forward fill
bysort id (date): replace value = value[_n-1] if missing(value)
```

## if and in Qualifiers

### if Qualifier
```stata
summarize income if age > 25
count if age >= 18 & age <= 65
gen eligible = 1 if (age >= 18 & citizen == 1) | (age >= 21 & resident == 1)
list if inlist(state, 1, 2, 5, 10)
count if inrange(age, 18, 65)
```

**Gotcha:** Wildcards (`*`) do NOT work in `if` expressions. They only work in variable lists.

### in Qualifier
```stata
list in 1/10          // First 10
list in -10/l         // Last 10 ('l' = last)
list in f             // First observation
```

When combined, `in` is evaluated first, then `if`.

## Variable Lists and Wildcards

```stata
describe age-education       // Range of variables
summarize inc*               // Wildcard at end
describe *_id                // Wildcard at beginning
drop _*                      // Variables starting with underscore

// By variable type
ds, has(type numeric)        // All numeric variables
ds, has(type string)         // All string variables
ds, has(vallabel)            // Variables with value labels
```

## Temporary Variables

Automatically deleted when program/do-file ends.

```stata
tempvar sumsq
gen `sumsq' = x^2          // Reference with backticks

tempname myscalar mymatrix  // For scalars/matrices
scalar `myscalar' = 100

tempfile mydata             // For temporary datasets
save `mydata'
```

**Key features:**
- Automatic cleanup (even on error)
- Unique names guaranteed by Stata
- Scoped to the program/do-file where created
- Reference with backticks: `` `varname' ``

```stata
// Common pattern: preserve sort order
tempvar orig_order
gen `orig_order' = _n
sort age income
// ... operations ...
sort `orig_order'
```
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