Macros are very useful tools when writing do-files or anything more advanced. They're perfect for repetitive tasks when you don't want to write out long lists of variables (or of anything else) repeatedly.
Macros in Stata come in two forms-global and local. Global macros can be used for any purpose in that session of Stata. For example, you can declare a global macro in the command line prompt and use that in any do-file or ado-file. The reverse is also true.
Local macros are confined to the area in which they're defined. If you create on in a do-file, you can only use it in that particular do-file. If you define it in at the command line prompt, it will not be available in any do-file.
global mname item1 item2 ...
to recover (in do file or in stata): use $mname
local mname item1 item2
to recover (in do file or in stata): use `mname'
If you have a defined macro (or multiple defined macros), there are some operations you can perform on them. I have split the commands into two types - cmd and oper. cmd is a command on a single macro while oper requires two macros.
local/global macname : list cmd macname
| cmd | description | Example |
|---|---|---|
| uniq | Extracts the unique elements of the macro | uniq "A B C B" returns "A B C" |
| dups | Extracts the repeated elements of the macro | dups "A B C B" returns "B" |
| sort | Alphabetizes the elements of the macro | sort "A B C B" returns "A B B C" |
| retokenize | ||
| clean | ||
| sizeof | Returns the number of elements |
local/global macname : list macro1 oper macro2
| oper | description | Example |
|---|---|---|
| | | Returns the union of both macros | "A B C" | "A C D" returns "A B C D" |
| & | returns the intersection of both macros | "A B C" & "A C D" returns "A C" |
| - | returns elements of macro1 less the elements that are present in macro2 | "A B C" - "A C D" returns "B" |
| == | tests whether macro1 is identical to macro2 regardless of order | "A B C" == "A C B" returns 1 |
| === | tests whether macro1 is identical to macro2 including order | "A B C" == "A C B" returns 0 |
| in | tests whether all elements of macro1 are present in macro2 | "A B C" in "A C D E B" returns 1 |