Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 36 ยท Programming and Do-files

Macros: Local, Global and Extended Functions

Understand Stata macros: local and global definitions, the quote syntax, expressions, extended macro functions, tempvar, scalars and a macro-expander stand-in.

A macro in Stata is a named piece of text. Where the macro's name appears, Stata replaces it with the text before running the command. That simple substitution is the foundation of almost every reusable script: a list of control variables stored once and used in five regressions, a file path defined at the top, the result of one command fed into the next.

Stata cannot run on this site; its code is read-only here. The runnable block is a tiny Python macro expander that imitates how Stata substitutes text, so you can experiment with the quoting rules.

Local macros

A local exists only within the do-file (or program, or interactive session) that created it.

STATA
local controls age educ exper i.region
regress wage `controls'
regress lnwage `controls' union
display "`controls'"

You define a local without the quotes, local controls ..., and use it with a left single quote (the backtick, usually top-left on the keyboard) and a right single quote (the apostrophe): `controls'. The two marks are different characters, and mixing them up is the most common macro bug.

Locals are overwritten freely: local x 5 then local x = x' + 1. The =` sign evaluates an expression; without it, Stata stores the text literally:

STATA
local a 2+3         // stores the text "2+3"
local b = 2+3       // stores the number 5

Global macros

A global persists for the whole Stata session and is visible everywhere. Use it with a dollar sign.

STATA
global root "C:/work/project"
use "$root/data/clean/survey.dta", clear
display "${root}/output"      // braces mark the end of the name

Globals are handy for paths set once in the master do-file, but they are risky for anything else: any script can change them, and clear all removes them. Prefer locals, and pass values to programs through arguments.

Where macro values come from

Stata commands store results that you can read into macros:

STATA
summarize wage
local avg = r(mean)
local n   = r(N)
display "Mean wage across `n' people: " %5.2f `avg'

regress wage educ
local b = _b[educ]
local se = _se[educ]

r() holds results from general commands, e() from estimation commands, and _b[] and _se[] hold coefficients and standard errors. Use return list, ereturn list and matrix list e(b) to see what is available.

Extended macro functions

local name : function gives you information about variables and files:

STATA
local lbl  : variable label wage
local type : type wage
local nvars : word count `controls'
local first : word 1 of `controls'
local files : dir "data/raw" files "*.csv"

You can store lists of variables, for instance all numeric variables, with ds, has(type numeric) and then local numvars r(varlist)'`.

Temporary objects

Scripts that create helper variables should not leave them behind or collide with existing names. Stata provides temporary names that disappear automatically:

STATA
tempvar sq
generate double `sq' = wage^2
tempname m
scalar `m' = r(mean)
tempfile helper
save `helper'

tempvar names variables, tempname scalars and matrices, tempfile files. They are most useful inside programs and loops.

Scalars and matrices

Macros hold text. For exact numbers, use scalars:

STATA
scalar alpha = 0.05
display invnormal(1 - alpha/2)
matrix B = e(b)

A scalar keeps full double precision, whereas a macro holding a number may convert it to text with limited digits unless you use =. For tables, matrix and mata are available.

Stand-in: a macro expander

This Python block imitates the substitution step: it keeps dictionaries for locals and globals and replaces `name' and $name in a line. It also shows what happens when a macro is undefined, which Stata treats as an empty string.

Python Macro substitution (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.

The last line prints regress wage with nothing after it. Stata would then run a regression of wage on no predictors without warning. Catching a typo like this is a good reason to use assert and to read your log.

Counting and arithmetic with locals

Python Loop counter with a local (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.

Common mistakes

  • Mismatched quotes: `x" or 'x' do nothing useful.
  • Forgetting = when you want arithmetic.
  • Using a local created in one do-file from another, or after a program ends.
  • Putting a macro in double quotes when it contains quotes itself; use compound quotes `"..."'.
  • Leaving globals around and getting results that depend on the session. macro list prints all of them, and macro drop _all clears them.

Now put macros to work in loops.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How do you read the value of a local macro named controls?

    Locals use a left backtick and a right apostrophe; $name is for globals.
  2. 2. What does local b = 2+3 store?

    With the equals sign Stata evaluates the expression; without it, the text is stored as is.
  3. 3. Where is a local macro defined in a do-file visible?

    Locals are scoped to the level where they were defined; globals persist for the session.
  4. 4. What does tempvar do?

    Temporary names avoid clashes and clean up after themselves.

Summary

  • A macro is text substituted before a command runs: locals with `x', globals with $x.
  • Use = to evaluate, extended macro functions to inspect variables and files, and r()/e() results to capture numbers.
  • tempvar, tempname and tempfile keep scripts tidy; scalars hold exact numbers.
  • The Python expander is a stand-in for Stata's substitution.

Next: Loops with foreach and forvalues