No history yet

Programming Basics

Automate Your Analysis with Do-files

So far, you've been typing commands directly into Stata's command window. This is great for exploring data, but what if you need to run the same set of commands again? Or share your analysis with a colleague? This is where do-files come in.

A do-file is a simple text file that contains a sequence of Stata commands. Think of it as a script or a recipe for your analysis. By saving your commands in a do-file, you create a reproducible record of your work. Anyone (including your future self) can run the file and get the exact same results.

To create one, you just open Stata's Do-file Editor (or any text editor), type your commands, and save the file with a .do extension.

For example, you could save the following commands in a file named analysis.do:

/* 
  My First Do-File
  This script loads the auto dataset and runs a simple regression.
*/

// Load the dataset
sysuse auto, clear

// Summarize the price and mpg variables
summarize price mpg

// Run a regression
regress price mpg

Notice the comments. Anything between /* and */ is a multi-line comment, and anything after // is a single-line comment. Stata ignores these, but they are crucial for explaining your code to others and remembering your own thought process.

To run this file, you simply type do analysis.do in the command window. Stata will execute each command in order, just as if you had typed them one by one.

Repeating Tasks with Loops

Often, you'll find yourself performing the same action on multiple variables. For instance, you might want to generate summary statistics for a list of variables. You could type the summarize command for each one, but there's a much more efficient way: loops.

A loop repeats a block of commands for each item in a list. The foreach loop is one of Stata's most useful tools for automation.

Imagine you want to see the summary statistics for price, mpg, and weight. Instead of three separate commands, you can use a loop:

foreach var of varlist price mpg weight {
  summarize `var'
}

Let's break this down. foreach var of varlist price mpg weight tells Stata to create a temporary placeholder, or a "local macro," named var. It will then loop through the block of code inside the curly braces { }, once for each variable in the list.

The first time through, var holds the value price. The command inside the loop becomes summarize price. The second time, var holds mpg, so Stata runs summarize mpg. Finally, it runs summarize weight.

Notice the special single quotes around var inside the loop: `var'. This syntax tells Stata to substitute the placeholder with its current value. This is a key concept for programming in Stata.

Making Decisions with Conditionals

Your analysis might need to change based on certain conditions. For example, you might want to run a command only if a specific condition is met. This is where if and else statements come in. They allow your do-file to make decisions and follow different paths.

You've already used the if qualifier to filter data for a single command (e.g., summarize mpg if foreign==1). The if command is different; it controls whether whole blocks of code are executed.

Let's see an example. Suppose we want to create a new variable, but only if it doesn't already exist. We can use a local macro and a conditional check.

// Let's count how many variables start with 'm'
// The `: list sizeof` part counts the elements in the macro `vars`
unab vars : m*
local count : list sizeof vars

// Now, we use the if command
if `count' > 0 {
  display "Found `count' variable(s) starting with 'm':"
  display "`vars'"
} 
else {
  display "No variables starting with 'm' found."
}

Here, unab vars : m* finds all variables that start with the letter 'm' and stores their names in a local macro called vars. Then, local count : list sizeof vars counts how many variables were found and stores that number in a macro called count.

The if count' > 0command checks if the value stored incountis greater than zero. If it is, Stata executes the code inside the first set of curly braces. If not, it skips to theelse` block and runs that code instead. This allows your do-file to adapt to different situations dynamically.

Creating Custom Commands

As your do-files get more complex, you might find yourself reusing the same chunk of code. Stata allows you to bundle these chunks into your own custom commands, called "programs." A program is a set of commands that you can define once and then call by name whenever you need it, just like any built-in Stata command.

Defining a program is straightforward. You start with program define, give your program a name, write your code, and finish with end.

// Define a new program called 'regsum'
program define regsum
  // Use syntax to specify that we expect one variable name
  syntax varlist(min=1 max=1)

  // Run a regression with mpg as the dependent variable
  regress mpg `varlist'

  // Get summary stats for the predictor variable
  summarize `varlist'
end

This code defines a program named regsum. The line syntax varlist(min=1 max=1) tells Stata that this command requires exactly one variable as an input. Inside the program, Stata will place that variable name into the local macro varlist.

Once the program is defined (by running this code once), you can use regsum just like any other command.

To run a regression of mpg on weight and then summarize weight, you would simply type: regsum weight

To do the same with the length variable, you'd type: regsum length

This simple program saves you from typing two commands each time. By combining do-files, loops, conditionals, and programs, you can automate even the most complex and repetitive parts of your data analysis.

Quiz Questions 1/6

What is the primary purpose of a Stata do-file?

Quiz Questions 2/6

In a Stata do-file, a single-line comment starts with // and a multi-line comment is enclosed by /* and */.

You've now learned the building blocks of Stata programming. These tools will help you work more efficiently and produce analysis that is transparent and easy to reproduce.