2. Stata Best Practices

“Any fool can write code that a computer can understand. Good programmers write code that humans can understand.” – Martin Fowler

Lesson Prerequisites

This lesson assumes that you have completed the Intro to Stata bootcamp lesson.

Intro to the Lesson

This lesson will give you some tips on how to write clear and efficient code in Stata and in other programming languages. As with the Intro to Stata lesson, follow along with the videos by loading the dataset and attempting every command on your own console. Pause the video and troubleshoot commands as needed.

1. Principles of writing good .do files (1)

Commenting, organizing, and formatting your code are the first steps toward making it comprehensible to collaborators, including your future self.

2. Principles of writing good .do files (2)

Specifying your working directory, naming conventions, writing modular code, and approaches to reviewing code are important skills for writing clear code in Stata.

3. Macros

Macros are placeholders for text or numbers, either created by the user or by Stata after a calculation command, that can make your code a lot less error-prone.

4. Loops

Loops can be used to automate tasks, which can save you a lot of time and reduce the number of errors in your code. We talk about foreach and forvalues loops in this lesson.

5. bysort

The bysort command, along with the use of system variables like _n and _N, can allow you to repeat commands across subgroups in your dataset.

Additional Resources

Banner photo: Anscombe's quartet, showing how data with the same summary statistics can represent very different relationships between two variables. Accessed from https://en.wikipedia.org/wiki/Anscombe%27s_quartet#/media/File:Anscombe's_quartet_3.svg.