Differences between revisions 1 and 2
Revision 1 as of 2021-03-16 02:09:28
Size: 1486
Comment:
Revision 2 as of 2021-03-16 02:09:41
Size: 1487
Comment:
Deletions are marked like this. Additions are marked like this.
Line 44: Line 44:
100 vs. _N 100 vs. 100

Macros

Stata offers a set of macro features, each with slightly different behavior.


Globals

Global macros are declared with the global command. Generally these are discouraged, because their very nature (i.e. globally available) creates side-effects.

global my-vars var1 var2
display "$my-vars appears as 'var1 var2'"
display "${my-vars} appears the same"

Locals

Local macros are declared with the local command, and only exist in the local scope.

local my-vars var1 var2
display "`my-vars' appears as 'var1 var2'"

Evaluation

If a macro definition includes an equals sign (=), then what follows is evaluated as an expression.

. local count1 = _N
. local count2 _N
. display "`count1' vs. `count2'"
100 vs. _N
. display "`count1' vs. " `count2'
100 vs. 100

Loops

Loops implicitly create local macros, which are accessed the same way.

foreach var of varlist var* {
  display "I found `var' while looping through all variables matching 'var*'"
}

foreach var of local my-vars {
  display "I found `var' while looping though `my-vars'"
}

Scalars

Scalars are essentially (and often used as) a global macro. The distinguishing behavior is seen in arithmetic.

. local i=-2
. display `i'^2
-4
. display (`i')^2
4
. scalar j=-2
. display j^2
4


CategoryRicottone

Stata/Macros (last edited 2023-07-28 21:22:48 by DominicRicottone)