Written and maintained by CASRAI Editorial Board
Published
On this page
Stata code consists of commands and procedural scripts written in Stata’s specialized statistical domain language to execute data transformations, econometric modeling, biostatistical analysis, and publication-grade reporting. Unlike point-and-click statistical menus, writing Stata code enables research teams to construct automated, self-documenting workflows where every data transformation and statistical calculation is recorded in plaintext script files known as do-files (reproducible Stata do-files). Stata evaluates commands through a unified language grammar that governs argument placement, conditional filtering, and option assignment, while returning structured scalar, vector, and matrix results into temporary memory buffers. Whether running an exploratory regression interactively or submitting headless batch pipelines on a high-performance computing cluster, mastering Stata code ensures empirical findings remain fully reproducible across collaborative research environments.
What it is used for in research
In quantitative academic and policy research, Stata code serves as the core scripting language across economics, epidemiology, sociology, public policy, and political science. Empirical researchers rely on Stata’s syntax engine because its commands are purpose-built for tabular observational data, complex survey sampling designs, longitudinal panels, and causal inference. Where general-purpose programming languages require extensive library configurations and manual matrix declarations for standard econometric tasks, Stata commands bundle sophisticated statistical estimators into concise, auditable expressions.
Research workflows utilize Stata code across four primary administrative and analytical domains:
- Data Wrangling and Harmonization: Cleaning longitudinal surveys, restructuring wide patient records into long person-period files with the
reshapecommand, creating index variables, and executing deterministic joins usingmerge 1:1ormerge m:1with comprehensive status audits. Researchers frequently automate systematic recoding pipelines by recoding variables in Stata to standardize survey indicators. - Econometric and Statistical Modeling: Estimating high-dimensional fixed effects, instrumental variables (
ivregress), difference-in-differences, generalized linear models, survival curves (stsetandstcox), and multinomial discrete choice models. Stata code applies clustering corrections, heteroskedasticity-consistent covariance matrices, and complex survey weights (svyset) across all core estimators. - Postestimation Diagnostics and Marginal Effects: Computing predicted probabilities, marginal effects at representative values (
margins), linear hypothesis tests (test), and contrast matrices without manual algebraic re-estimation. - Automated Replication Packages: Packaging publication replication archives required by leading academic journals. Authors assemble master do-files that execute data preprocessing, model fitting, and automated table generation, outputting formatted LaTeX, Microsoft Word, or HTML tables through commands such as
etable,putdocx, and community packages discovered via the Stata search command.
When working in multi-investigator projects, managing shared repositories of stata codes requires rigorous coding standards. Teams establish shared variable dictionaries, enforce version control statements, and structure script hierarchies into numbered sequences (e.g., 01_import.do, 02_clean.do, 03_estimate.do, 04_tables.do) overseen by a single driver script. This prevents conflicting data definitions and guarantees that any team member or peer reviewer can reproduce the entire paper from raw data files in a single execution run.
Install or access (official source only)
Stata is proprietary commercial statistical software developed and maintained exclusively by StataCorp LLC. Official installation media, license certificates, and platform binaries must be obtained directly from StataCorp (stata.com) or through authorized university and institutional software portals.
Stata is distributed in three distinct operational editions that share an identical core command syntax but differ in computational scale and multi-core processor support:
- Stata/MP (Multi-Processor): The high-performance edition engineered for multi-core workstations and high-performance computing (HPC) clusters. Stata/MP parallelizes matrix operations and estimation algorithms across 2 to 64 CPU cores, drastically accelerating estimation on datasets with millions of observations.
- Stata/SE (Standard Edition): Designed for large datasets, accommodating up to 2,048 variables and billions of observations, constrained only by available physical system memory (RAM).
- Stata/BE (Basic Edition): Tailored for introductory statistical analysis and smaller datasets, supporting up to 2,048 variables and up to 2.14 billion observations with single-core processing.
Institutional researchers typically access Stata through campus site licenses, dedicated computing virtual machines, or local desktop installations. Setting up the software requires a formal license certificate containing a Serial Number, Code, and Authorization String, as detailed in our guide to Stata licence types. On Linux servers and headless computing environments, system administrators deploy Stata via command-line tarball extraction, configuring environment path variables so that the executables (such as stata, stata-se, or stata-mp) are available across user shell sessions.
To verify that an existing installation is current, open Stata and run:
update query
If official patches, security fixes, or documentation updates are available from StataCorp’s update servers, applying them requires administrative privileges and running:
update all
Step-by-step task (numbered, with menu names or commands exactly as in the current docs)
Writing reliable Stata code requires adhering to the official command syntax grammar and organizing commands into structured, automated do-files. Follow this eight-step workflow to build an auditable, reproducible analysis script from environment initialization to headless batch execution.
Step 1: Initialize the script header and set version control
Open Stata’s Do-file Editor by clicking Window > Do-file Editor > New Do-file (or pressing Ctrl+9 on Windows / Cmd+9 on macOS). Begin every Stata script with an explicit version statement, memory clearing directives, and environment flags:
*====================================================================*
* Project: Empirical Labor Analysis
* Script: 01_wage_regression.do
* Author: Research Team
* Date: 2026-11-13
*====================================================================*
version 18
clear all
macro drop _all
set linesize 80
set more off
The version 18 command instructs Stata’s interpreter to execute all subsequent syntax under Stata 18 rules, safeguarding your code against breaking changes in future releases. clear all removes existing datasets, value labels, matrices, and scalars from memory, while macro drop _all eliminates lingering global macro definitions that could unintentionally alter logical branches.
Step 2: Initialize automated session logging
Scientific integrity requires recording all executed code and console output into an immutable log file. Initialize logging immediately after the environment header:
capture log close
log using "wage_analysis.log", text replace
The capture log close directive cleanly terminates any open log session without returning an error code. Specifying the text option ensures the log is written in standard plaintext rather than Stata’s binary SMCL (Stata Markup and Control Language) format, enabling direct viewing in Git diffs and third-party text editors.
Step 3: Load data and perform structural inspections
Load your target dataset and inspect variable classifications, storage types, and missing value distributions:
sysuse auto, clear
describe
codebook make price mpg weight foreign, compact
summarize price mpg weight, detail
The describe command outputs dataset metadata, including total observations, variable counts, and storage allocations (e.g., int, float, strL). The codebook, compact command provides a rapid audit of unique observation counts and missing data flags across your analytical variables.
Step 4: Transform data and engineer model features
Execute variable transformations using Stata’s strict syntax grammar. For mathematical creation, use generate; for updating existing variables conditionally, use replace:
* Create weight in metric tons
generate double weight_tons = weight * 0.00045359237
label variable weight_tons "Vehicle weight in metric tons"
* Generate standardized efficiency categories
generate byte high_mpg = (mpg >= 25) if !missing(mpg)
label variable high_mpg "High fuel efficiency indicator (mpg >= 25)"
label define lbl_efficiency 0 "Standard Efficiency" 1 "High Efficiency"
label values high_mpg lbl_efficiency
* Verify the frequency distribution
tabulate high_mpg foreign, missing
Notice the defensive coding practice if !missing(mpg). In Stata, numeric missing values (represented by a period .) are evaluated as positive infinity. Writing generate high_mpg = (mpg >= 25) without checking for missing values would erroneously classify missing observations as 1 (True).
Step 5: Estimate the econometric model using official syntax
Stata’s universal command syntax follows the structural blueprint defined in Stata User’s Guide [U] 11:
[by varlist:] command [varlist] [=exp] [using filename] [if exp] [in range] [weight] [, options]
Execute an Ordinary Least Squares (OLS) regression modeling vehicle price as a function of efficiency, metric weight, and manufacturing origin, requesting heteroskedasticity-robust standard errors via the options clause:
regress price mpg weight_tons i.foreign, vce(robust)
In this statement, regress is the command verb; price is the primary dependent variable argument; mpg weight_tons i.foreign forms the independent variable list (where factor variable notation i.foreign automatically expands categorical indicators and designates a base reference level); and vce(robust) is an option specified after the comma that modifies variance-covariance estimation using the Huber-White sandwich estimator.
Step 6: Execute postestimation testing and marginal analysis
Immediately after model estimation, Stata preserves model coefficients and variance-covariance matrices in system memory. Run postestimation hypothesis tests and compute predictive margins:
* Test the null hypothesis that foreign and domestic price coefficients are zero
test i.foreign
* Compute average marginal effects of vehicle weight
margins, dydx(weight_tons)
* Calculate predicted values and residuals
predict double price_hat, xb
predict double resid_val, residuals
Step 7: Automate repetitive workflows with local macros and loops
To reduce code duplication across multiple covariates, leverage Stata’s macro processor. Local macros exist only within the execution scope of the active script:
local continuous_covariates "mpg weight_tons length turn"
foreach var of local continuous_covariates {
quietly summarize `var'
display "Variable: " as yellow "`var'" ///
" | Mean: " as result %9.2f r(mean) ///
" | Std Dev: " as result %9.2f r(sd)
}
The macro reference `var' evaluates dynamically on each iteration, substituting the variable name directly into the syntax stream prior to command execution.
Step 8: Close logs and run in headless batch mode
Conclude your script by closing the log file:
log close
exit, clear
To execute this entire do-file without launching Stata’s graphical interface (such as on an automated nightly server or an institutional Linux cluster), trigger Stata from your operating system command shell.
On Linux, Unix, or macOS Terminal, run:
stata -b do 01_wage_regression.do &
On Windows Command Prompt, run:
stata /b do 01_wage_regression.do
The -b (Unix) and /b (Windows) flags execute Stata in non-interactive batch mode, suppressing all graphical dialogs and directing all command output directly into 01_wage_regression.log in the active working directory.
Output and how to read it
When Stata executes a statistical command, it formats results into standardized terminal tables and saves underlying calculations into structured return classes. Understanding both the visual console output and the internal return buffers is essential for interpreting results and automating downstream tables.
Reading the Regression Output Table
Consider the console output returned from running regress price mpg weight_tons i.foreign, vce(robust):
Linear regression Number of obs = 74
F(3, 70) = 17.29
Prob > F = 0.0000
R-squared = 0.5249
Root MSE = 2073.4
------------------------------------------------------------------------------
| Robust
price | Coefficient std. err. t P>|t| [95% conf. interval]
-------------+----------------------------------------------------------------
mpg | -76.8188 65.3121 -1.18 0.243 -207.0792 53.4416
weight_tons | 6675.293 1182.49 5.65 0.000 4316.892 9033.694
|
foreign |
Foreign | 3673.064 683.978 5.37 0.000 2308.913 5037.216
_cons | -4952.723 3616.56 -1.37 0.175 -12165.73 2260.285
------------------------------------------------------------------------------
The console output is divided into two distinct sections:
- Model Summary Header (Top Right):
Number of obs (74): The sample size utilized after dropping observations with missing values across model variables.F(3, 70) = 17.29: The joint Wald test statistic evaluating whether all non-intercept slope coefficients equal zero simultaneously. With 3 degrees of freedom in the numerator and 70 in the denominator,Prob > F = 0.0000indicates the model is statistically significant at standard significance levels (α < 0.001).R-squared (0.5249): The coefficient of determination, indicating that approximately 52.5% of the total variation in vehicle prices is explained by fuel efficiency, weight, and foreign origin.Root MSE (2073.4): The root mean squared error, representing the standard deviation of the regression residuals.
- Parameter Estimation Table:
Coefficient: The estimated point estimate (β). For example,weight_tons (6675.293)indicates that holding origin and fuel efficiency constant, each additional metric ton of vehicle weight is associated with an average price increase of 6,675.29 currency units.Robust std. err.: The heteroskedasticity-consistent standard error of the estimator.t and P>|t|: The test statistic under the null hypothesis (β = 0) and the two-sided p-value. Values whereP>|t| < 0.05indicate rejection of the null hypothesis at the 5% significance level.[95% conf. interval]: The range of values containing the true population parameter with 95% confidence under standard asymptotic assumptions.
Inspecting Stored Results and Return Classes
Stata does not force researchers to scrape printed screen text to retrieve figures. Every command automatically posts its underlying results into one of four system return classes:
- r-class: General calculation commands (e.g.,
summarize,tabulate,correlate) store results in memory bufferr(). Typereturn listto inspect all available elements. For instance, after runningsummarize price, Stata stores the sample mean inr(mean), observation count inr(N), and variance inr(Var). - e-class: Estimation commands (e.g.,
regress,logit,xtreg) store results in memory buffere(). Typeereturn listto display all stored model matrices, scalars, and strings. The coefficient vector is saved in matrixe(b), the variance-covariance matrix ine(V), sample size ine(N), and residual degrees of freedom ine(df_r). - c-class: System constants and operating environment settings stored in
c(), such as current machine date (c(current_date)), Stata version (c(version)), memory allocations, and directory paths. - s-class: Parsing subroutines that store temporary text tokens in
s()during syntax parsing.
To programmatically extract a regression coefficient and its standard error into a custom calculation, access the return vectors directly:
* Extract the coefficient and robust variance for weight_tons
scalar b_weight = _b[weight_tons]
scalar se_weight = _se[weight_tons]
display "Estimated Weight Effect: " %9.2f b_weight " (SE: " %9.2f se_weight ")"
The dataset table below details the formal syntax clauses of Stata’s language grammar, their ordering rules, and evaluation mechanics.
Troubleshooting
When Stata encounters an invalid command, missing variable, or algorithmic failure, execution halts and Stata outputs a distinctive error message accompanied by a numerical return code formatted as r(#). The table and troubleshooting steps below detail the most common Stata coding errors and their exact remedies.
Common Stata Return Codes and Solutions
- Error r(198) — invalid syntax: Occurs when command options are placed before a required variable list, when options are omitted after an unescaped comma, or when macro evaluation produces unbalanced quotation marks.
Remedy: Check the official command syntax usinghelp <command>. Ensure options appear strictly after the comma delimiter. When working with string macros containing embedded spaces, enclose macro references in compound double quotes (e.g.,`"`my_macro'"`). - Error r(111) — variable not found: Stata is strictly case-sensitive. Calling
summarize Pricewhen the variable is stored aspricecauses an immediate halt. This error also occurs if a variable was filtered out, renamed, or misspelled.
Remedy: Executedescribeorlookfor <keyword>to confirm the exact spelling and case. To prevent accidental truncation errors, configureset varabbrev offin your master script. - Error r(109) — type mismatch: Triggered when numeric mathematical operations are attempted on a variable stored as a string, or when passing string identifiers into regression formulas.
Remedy: Inspect data types withdescribe. Convert numeric strings usingdestring varname, replaceor categorical strings into numeric factor variables usingencode varname, generate(newvar). - Error r(459) — variable is strL: Occurs when legacy matrix or tabulation commands attempt to evaluate long string or binary storage types (
strL).
Remedy: Cast the variable to a standard short string usinggenerate str80 short_var = substr(strl_var, 1, 80)prior to tabulation. - Error r(9) — assertion is false: Emitted when an explicit data integrity validation statement (e.g.,
assert price > 0orassert inlist(gender, 1, 2)) encounters violating rows.
Remedy: Isolate the violating observations before proceeding: runlist make price if price <= 0to inspect anomalies and document data cleaning choices.
Advanced Script Debugging Techniques
When a complex do-file spanning multiple loops or nested programs fails without an obvious syntax error, activate Stata’s trace facility:
set trace on
set tracedepth 1
do 01_wage_regression.do
set trace off
With set trace on, Stata displays each line of code immediately after macro expansion, showing the exact evaluated values that caused the parser to trip. Limiting tracedepth to 1 prevents the console from being flooded with internal subroutines executed inside community-written ado-files.
Free alternatives
While Stata provides a tightly integrated statistical environment with extensive commercial documentation, several open-source and free software platforms offer robust capabilities for statistical analysis, econometric modeling, and reproducible research. The decision to write scripts in Stata versus an open-source alternative depends on team programming proficiency, computational scale, and publication licensing constraints.
| Software Tool | Primary Language Syntax | In-Memory Data Model | Econometrics & Modeling Focus | CLI Batch Execution | Licensing & Cost |
|---|---|---|---|---|---|
| Stata | Stata Command Language & Mata | Single tabular dataset (Frames in Stata 16+) | Observational data, panel estimators, survey analysis | Native (stata -b do / stata /b do) |
Commercial proprietary license |
| R | R (S-language dialect, functional) | Multiple data frames in memory simultaneously | High-dimensional fixed effects (fixest), biostatistics |
Native (Rscript script.R) |
Open source (GPLv2 / GPLv3) |
| Python | Python (object-oriented / procedural) | Multiple DataFrames (pandas, polars) |
Econometric modeling (statsmodels, linearmodels) |
Native (python script.py) |
Open source (PSF License, BSD) |
| GNU PSPP | SPSS command syntax (4GL) | Single active data matrix | Descriptive statistics, basic linear models, t-tests | Native (pspp script.sps) |
Open source (GPLv3) |
| Gretl | hansl scripting language & GUI | Single structured dataset matrix | Time-series, panel data, simultaneous equation models | Native (gretlcli -b script.inp) |
Open source (GPLv3) |
| Julia | Julia (multiple dispatch, technical) | Multiple DataFrames via typed column arrays | Fast structural estimation (FixedEffectModels.jl) |
Native (julia script.jl) |
Open source (MIT License) |
Researchers weighing statistical platforms can consult our detailed R vs. Stata comparison to evaluate differences in syntax paradigms, package management, and econometric modeling workflows.
FAQ
What is the difference between a Stata do-file and an ado-file?
A Stata do-file (.do) is a user script that contains a sequential batch of Stata commands executed to clean data, run models, and generate outputs for a specific project. An ado-file (.ado, short for “automatic do-file”) defines a custom, modular command or program using Stata’s program define syntax. When a user types a command that Stata does not recognize as an internal built-in kernel routine, Stata searches its ADO paths (including official base paths and community SSC directories) for an ado-file matching the command name and loads it into memory on demand.
How do local macros differ from global macros in Stata code?
Local macros are declared using local name "value" and referenced using asymmetric accent marks (`name'). A local macro exists only within the memory scope of the specific script, do-file, or program block currently executing; once the script finishes or halts, the local macro is purged from memory. Global macros are declared using global name "value" and referenced using a dollar sign prefix ($name). Global macros persist across all do-files and interactive sessions until explicitly cleared with macro drop. Best practices in reproducible coding favor local macros because global macros can cause unintended variable collisions across collaborative scripts.
How do you run Stata code in batch mode on a remote Linux server or HPC cluster?
To execute Stata code on a remote Linux cluster without launching the graphical desktop, invoke the Stata binary from the terminal using the -b flag followed by the do directive and your script path: stata -b do my_analysis.do &. To ensure the process does not terminate if your SSH connection drops, prefix the command with nohup: nohup stata-mp -b do my_analysis.do &. Stata automatically redirects all standard output and error messages into a plaintext log file named my_analysis.log in the directory from which the command was invoked.
Why does Stata return error r(111) variable not found when the column appears in my data?
The most common cause of error r(111) is case sensitivity. Stata treats variable names in a strictly case-sensitive manner; an uppercase variable GDP cannot be referenced as gdp. Other frequent causes include hidden leading or trailing spaces in variable names imported from external spreadsheets, variable abbreviations resolving to multiple candidate columns when set varabbrev on is active, or earlier data-cleaning commands (such as drop or keep) removing the variable before the current line executes.
How can researchers verify which values are saved by a Stata command after execution?
After running any Stata command, researchers can inspect the temporary memory buffers to view stored results. For general computation, data summary, or testing commands (r-class commands such as summarize, tabstat, or correlate), type return list to display all stored scalars, macros, and matrices. For estimation and regression commands (e-class commands such as regress, logit, or xtreg), type ereturn list to display the stored coefficient vectors, covariance matrices, and model fit statistics.
Can Stata code handle multiple datasets in memory simultaneously?
Starting with Stata 16, Stata supports multiple datasets residing in system memory at the same time through its “Frames” architecture. Prior to Stata 16, Stata could only hold a single rectangular dataset in memory, requiring researchers to save intermediate files to disk or use preserve and restore blocks. With Frames, researchers can create and switch between named datasets using frame create, frame change, and frame copy, as well as link datasets across frames without executing full disk joins using frlink.
Sources
- StataCorp LLC. (2026). Stata User’s Guide: [U] 11 Language syntax. Stata Press. https://www.stata.com/manuals/u11.pdf (Accessed 2026-11-13).
- StataCorp LLC. (2026). Stata User’s Guide: [U] 16 Do-files. Stata Press. https://www.stata.com/manuals/u16.pdf (Accessed 2026-11-13).
- StataCorp LLC. (2026). Stata Programming Reference Manual: [P] return and ereturn. Stata Press. https://www.stata.com/manuals/p.pdf (Accessed 2026-11-13).
- StataCorp LLC. (2026). FAQ: Running Stata for Windows in batch mode. StataCorp LLC. https://www.stata.com/support/faqs/windows/batch-mode-windows/ (Accessed 2026-11-13).
- StataCorp LLC. (2026). FAQ: Running Stata for Unix in batch mode. StataCorp LLC. https://www.stata.com/support/faqs/unix/batch-mode-unix/ (Accessed 2026-11-13).
- R Core Team. (2026). R: A Language and Environment for Statistical Computing. R Foundation for Statistical Computing. https://www.r-project.org/ (Accessed 2026-11-13).
- Free Software Foundation. (2026). GNU PSPP Statistical Analysis Software. Free Software Foundation. https://www.gnu.org/software/pspp/ (Accessed 2026-11-13).
Data: Stata Command Syntax Grammar and Language Elements
Structural breakdown of Stata command syntax clauses, parameter positions, optionality, evaluation orders, and parser rules compiled from the Stata User's Guide [U] 11 Language syntax.
| Syntax Clause | Formal Notation | Clause Position | Optional Status | Evaluation Order (sequence) | Functional Role |
|---|---|---|---|---|---|
| Prefix Modifier | [by varlist:] | Pre-command | Optional | 1 | Repeats the command across subsets defined by distinct values of varlist |
| Command Verb | command | Head | Mandatory | 2 | Specifies the core action, transformation, or estimation procedure to execute |
| Variable Arguments | [varlist] | Post-command | Optional | 3 | Specifies the target dependent, independent, or operational variables |
| Expression Assignment | [=exp] | Post-varlist | Optional | 4 | Supplies algebraic or boolean formulas required by data creation commands |
| External File Clause | [using filename] | Mid-clause | Optional | 5 | Designates an external filesystem path for reading or writing data |
| Logical Filter Clause | [if exp] | Subsetting clause | Optional | 6 | Restricts command evaluation to observations satisfying a boolean condition |
| Observation Range | [in range] | Subsetting clause | Optional | 7 | Restricts execution to specific row indices or observation number spans |
| Sampling Weight Clause | [weight] | Modifier clause | Optional | 8 | Applies analytical, frequency, importance, or sampling probability weights |
| Options Delimiter | [, options] | Terminal clause | Optional | 9 | Modifies algorithmic convergence, standard error estimation, or output format |
Sources
- Stata User's Guide: [U] 11 Language syntax (accessed 2026-11-13)
Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.







