Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 36 ยท Programming and Do-files

Do-files, Log Files and a Clean Script Layout

Write repeatable Stata do-files: header, version, clear all, set seed, relative paths, log using, comments, line breaks, run and do, plus a script-checker stand-in.

Typing commands in the Command window is fine for exploring. Anything you might need to run twice belongs in a do-file, a plain text file with the extension .do that holds Stata commands in order. A good do-file lets you, a colleague or a reviewer re-create every table and figure from the raw data with one click. This lesson shows the conventions that make that true.

Stata cannot run on this site, so Stata code is read-only. The runnable block is a small Python stand-in: a script checker that looks for the most common problems in a do-file text, so you can practise reviewing scripts.

Creating and running a do-file

Open the Do-file Editor with doedit, the toolbar icon or Ctrl+9. Save the file, then run it with the Execute button (Ctrl+D runs the whole file, or just the selected lines) or from the command line:

STATA
do "analysis/01_clean.do"
run "analysis/01_clean.do"    // same, but without echoing commands to the Results window

do shows every command as it executes; run is quiet and is better for helper scripts. From the operating system you can run Stata in batch mode, for example stata-mp -b do analysis.do on Linux or macOS, which writes a log file next to the script.

A reliable header

Start every do-file the same way:

STATA
/*==============================================
  01_clean.do
  Purpose : clean the raw survey and save analysis data
  Author  : A. Student
  Input   : data/raw/survey.csv
  Output  : data/clean/survey.dta
==============================================*/
version 18            // keep behaviour stable across Stata releases
clear all             // empty memory, programs, matrices, macros
set more off          // (Stata 18 does not pause by default)
set seed 20250101     // any random step becomes repeatable
capture log close
log using "logs/01_clean.log", replace text
  • version tells newer Stata releases to interpret the script the way the named version did. It matters most for random-number and bootstrap behaviour.
  • clear all guarantees you start from a blank state, so code that accidentally depends on something left from earlier fails immediately instead of silently.
  • capture log close closes any log left open by a previous failed run; capture swallows the error if none was open.
  • text makes the log a plain-text .log file (the default .smcl needs Stata to view).

Log files

A log is a record of everything in the Results window:

STATA
log using "logs/analysis.log", replace text
...
log close

Use append to add to an existing log or replace to overwrite. cmdlog records only commands. A set logtype text early on makes text the default. Logs are evidence: keep the one from the final run, and never edit it by hand.

Comments and long lines

STATA
* a whole line comment
summarize wage   // comment after a command
/* a block
   comment */
regress wage educ exper ///
        i.region i.industry, ///
        vce(cluster id)

/// joins a line to the next, so you can keep lines short. Do not put /// inside a block comment. Prefer descriptive comments about why, not what: * drop observations flagged as duplicates in the data-collection report beats * drop.

Paths and project layout

Hard-coded paths such as C:\Users\Ana\Desktop\project\data.dta break on any other computer. Set the working directory once and use relative paths:

STATA
cd "C:/work/myproject"                 // only line to edit per machine
use "data/clean/survey.dta", clear
save "output/tables/results.dta", replace

Use forward slashes, which work on every operating system, and quote paths with spaces. A tidy folder structure helps:

Text
myproject/
  data/raw/      never edited by hand
  data/clean/    produced by do-files
  analysis/      01_clean.do  02_models.do  03_figures.do
  output/        tables and graphs
  logs/
  master.do      runs everything in order

The master file is the entry point:

STATA
* master.do
version 18
clear all
global root "C:/work/myproject"
cd "$root"
do "analysis/01_clean.do"
do "analysis/02_models.do"
do "analysis/03_figures.do"

Read about the global in macros.

Stop silent failures

STATA
assert !missing(id)                    // stop if any id is missing
isid id year                           // stop if (id, year) is not unique
confirm file "data/raw/survey.csv"     // stop if file missing
capture noisily drop temp_var          // run, show errors, but do not stop

assert is the most valuable single command for data work. Stata stops with an error and the exact count of violating rows, which is far better than a quiet wrong result three tables later.

Stand-in: a do-file checker

This Python block scans a script and flags missing header items. It is not a Stata feature, just a way to practise the checklist above.

Python Do-file lint (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 sample script fails most checks. Fix it by adding the header from above, using relative paths and an assert, then run the checker on your improved version.

Other good habits

  • Number the scripts by order of execution and give each one one job (clean, merge, model, plot).
  • Never overwrite the raw data; write new files to a different folder.
  • Re-run the whole pipeline from the master do-file before sending results; if it fails, fix it.
  • Add timer on 1 ... timer off 1 and timer list to see how long a slow step takes.
  • Use display for messages, for example display "Sample size: " _N.
Python Why a seed matters (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 two runs with the same seed match; the unseeded run differs every time you press Run. In Stata, set seed plays the same role, and you should set it once near the top of any script that samples, simulates or bootstraps. Continue with macros to make scripts shorter and more flexible.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the difference between do and run?

    do displays each command as it executes; run executes quietly.
  2. 2. Why put clear all and version at the top of a script?

    A clean start exposes hidden dependencies and version keeps old scripts interpreted the same way.
  3. 3. What does /// do at the end of a line?

    Triple slash joins the next line to the current one, so long commands stay readable.
  4. 4. Which command stops a script if id is not unique within year?

    isid returns an error when the variables do not uniquely identify observations.

Summary

  • A do-file is a repeatable record: header, version, clear all, set seed, log using.
  • Use relative paths, a master do-file and numbered scripts with one job each.
  • assert, isid and confirm turn silent mistakes into loud ones.
  • The Python checker is a stand-in for practising the checklist.

Next: Macros: locals and globals