Tag Archives: macros

Nesting local macros in Stata

Local macros are a very useful feature of Stata. Here is a simple example.

local macro1 “Hello!”

local macro2 = “How are you?”

local macro3 2+2

local macro4 = 2+2

di ” `macro1'`macro2′ ”

di “Here’s some math: `macro3' = `macro4′ ”

 

A few comments are in order here.  macro1′ tells Stata to replace this expression with the contents of the local macro1. Make sure to leave no spaces inside the `’. Also, note how macro3 and macro4 lead to different outcomes. You need to use the equal sign to make Stata to evaluate the expression, otherwise it will treat it like a string.

Now, Stata applies the “parentheses rule” when replacing local macros for their contents. That is, it first replaces the innermost local macro, then the second innermost local macro, and so on. Here is an example.

local macro5 “nest”

local nestmacro “Local macros can be nested!”

di ” “macro5’macro’ ”

Let’s add another layer to the nesting of the previous example and play with it a little bit more:

local macro5 “nest”

local macro6 “macro”

local macro7 5

local nestmacro “Local macros can be nested!”

di ” “macro`macro7”`macro6” ”

I guess you have a pretty good idea of how this works now. Good luck in your Stata coding.

 

 

A few tips for programming in Stata

Stata is a very powerful and useful statistical software. Just like any sophisticated tool, it takes time to learn about it. And you need to invest some time to master it. Programming is one of those skills that knowing a little bit can be very beneficial. Below you will find four videos. The first video goes over the functionalities of the Stata Program Editor. The second video covers some basics of Stata commands. The third video talks about loops, which are an essential tool for programmers. Finally, the fourth video is about macros, which together with loops are very useful to handle repetitive tasks.

How to use the Stata Program editor:

Basics of Stata:

Quick guide to loops:

More about macros: