In this video, we’ll explore how to use do-files in Stata. By the end, you should understand what a do-file is and how to utilize it effectively.
A do-file in Stata is a script that lets you record and replay a series of Stata commands. It’s invaluable for automating repetitive tasks or long sequences of code. Instead of manually inputting every command each time, you can write them once in the do-file and simply run the script. This is also beneficial for recording the procedures of your analysis, such as data cleaning, variable labeling, and the steps leading to your results. Should you make a mistake or need to adjust something in your analysis, rather than starting from scratch, you can modify the relevant portion in your do-file, save it, and run it again.
But what exactly is a do-file? It’s a text file containing a series of Stata commands. When using the do-file editor in Stata, you input commands line by line, just as you would in the main command window. Each line in the do-file represents a command. When you run a do-file, Stata processes each of its commands sequentially. Notably, you can also call one do-file from within another. To execute a do-file, use the syntax: do “filename.do”.
For example, to run a do-file named “my_do_file”, you’d type: do “my_do_file.do”.
To create a new do-file, open the do-file editor. This interface resembles a text editor where you input your Stata commands. You can access the do-file editor by clicking the icon on Stata’s toolbar that looks like a notebook with a pencil. Inside the editor, there are several crucial buttons:
Create New Do File
Execute (a paper icon with a play button)
Lines that start with an asterisk (*) and appear green are comments. Stata won’t execute these; they’re simply notes or explanations you can embed within the do-file.
Demonstrating the do-file editor, I’ve written a script containing multiple steps we’ve discussed in previous tutorials. To add more code, place the cursor where needed and type your commands. Once finished, save the do-file. If there’s an error, like a misspelled command, Stata will indicate it when you try to execute the do-file. However, the advantage of a do-file is that you don’t need to retype all commands—just correct the mistake, save, and rerun.
To open the do-file editor, click its icon on Stata’s toolbar.
Input your commands into the editor, line by line.
Save your do-file regularly.
To run the do-file, click the “Execute” button on the toolbar.