Skip to content
Tutorials Center
My learning

Topics

Lesson 30 of 36 ยท Programming and Do-files

Writing Programs, ado-files and Stored Results

Write your own Stata commands with program define, syntax, tempvar, rclass and eclass results, ado-files and error handling, plus a Python stand-in.

A Stata program is a named block of commands that you can call with arguments, like any built-in command. Once you have copied the same ten lines three times, wrap them in a program. Good programs take their inputs through the syntax command, work on temporary variables, and return results in r() or e() so other commands can use them. Saved as an ado-file, they become available in every session.

Stata cannot run on this site, so all Stata code here is read-only. The runnable block is a Python stand-in that mimics a program with arguments, defaults and returned results.

A first program

STATA
capture program drop describe_var
program define describe_var
    version 18
    syntax varname [if] [in] [, Decimals(integer 2)]
    marksample touse
    quietly summarize `varlist' if `touse', detail
    display as text "Variable: " as result "`varlist'"
    display as text "  N     = " as result r(N)
    display as text "  Mean  = " as result %9.`decimals'f r(mean)
    display as text "  Median= " as result %9.`decimals'f r(p50)
end

describe_var wage if educ > 12, decimals(1)

Line by line: capture program drop removes an older copy, since Stata will not redefine a program that exists. program define name starts it and end finishes it. The syntax line declares what the user can type: one variable (varname), optional if and in, and an option decimals() that must be an integer with a default of 2. The capital letter in Decimals marks the shortest allowed abbreviation (d works). marksample touse creates a temporary 0/1 variable that is 1 for observations satisfying if, in and having no missing values for the variables, which you then pass to later commands as if touse'`.

The syntax command

The syntax command parses and checks the call for you. Common pieces:

Pattern Meaning
varlist One or more existing variables (varname for exactly one)
newvar A name for a variable that must not exist yet
[if] [in] Optional qualifiers
[, Option] An optional flag, tested with "option'" != ""`
Option(real 0.05) Numeric option with a default
[, Option(string)] String option
using/ A filename after using
[fweight] Frequency weights

If the user passes something invalid, Stata prints a standard error message automatically. You do not need to write checking code. Positional arguments without syntax are `1', `2' and `0' (the whole line), and args a b names them.

Returning results

Make a program return values so other code can use them:

STATA
capture program drop zscore_stats
program define zscore_stats, rclass
    syntax varname
    quietly summarize `varlist'
    return scalar mean = r(mean)
    return scalar sd   = r(sd)
    return scalar n    = r(N)
    return local  name "`varlist'"
end

zscore_stats wage
display r(mean)
return list

rclass programs store results in r(), which is overwritten by the next r-class command. Estimation commands use eclass with ereturn post and ereturn scalar, so that predict, test and estimates work. sreturn stores strings in s().

Temporary variables and clean-up

Inside programs, always use tempvar for helper variables so the user's data is untouched even if an error occurs:

STATA
program define standardize
    syntax varname, GENerate(name)
    confirm new variable `generate'
    tempvar m s
    quietly summarize `varlist'
    generate double `generate' = (`varlist' - r(mean)) / r(sd)
    label variable `generate' "`varlist' (z-score)"
end
standardize wage, generate(z_wage)

Use preserve and restore to change the data temporarily, but note that preserve takes time on large datasets. Use capture plus _rc for error handling, and exit 198 (or any return code with an error message) to stop with a clear message:

STATA
if `n' < 10 {
    display as error "too few observations"
    exit 2001
}

ado-files

Save the program in a file named exactly like the command, with the extension .ado: describe_var.ado. Put it in a folder on Stata's ado path, shown by adopath. The personal folder (sysdir's PERSONAL) is ideal for your own commands, and a project-local folder works with adopath ++ "ado" in the master do-file. Stata loads the file automatically the first time you type the command, so no do is needed. Add a help file describe_var.sthlp for documentation, and use which describe_var to see where a command comes from.

Programs defined in a do-file exist only until you clear all or exit. That is fine for one-off helpers inside a script.

User-written commands from the community (ssc install estout, ssc install reghdfe) are ado-files too; see regression tables for estout. For heavy numerical work, Mata, Stata's built-in matrix language, compiles to fast code and can be called from ado-files.

Stand-in: a program with arguments and returns

The Python function below imitates describe_var with a default option, an if-style filter and returned results. It is not Stata code, but the structure (parse, mark sample, compute, return) is the same.

Python A program with options and returns (Python stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Testing a program

Python Assert-style test of a function (Python stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

In Stata, the same idea is a small do-file that calls the program on tiny known datasets and uses assert and assert reldif() to compare results. Write at least one such test for each program you publish.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why start with capture program drop name?

    program define fails if the program already exists; capture ignores the error when it does not.
  2. 2. What does marksample touse do?

    The result is used as if touse in later commands inside the program.
  3. 3. Where do rclass programs store results?

    rclass uses return statements and r(); eclass uses ereturn and e().
  4. 4. How does Stata find an ado-file command automatically?

    Place name.ado on the ado path, and Stata loads it the first time you call name.

Summary

  • program define / end creates a command; syntax parses arguments and options; marksample handles if and in.
  • Return results with rclass or eclass; use tempvar and friends to avoid side effects.
  • Save as name.ado on the adopath to reuse; test with assert.
  • The Python functions are stand-ins that show the structure.

Next: Regression tables with estout and esttab