Saturday, December 22, 2012

Local-ize the Variable Label

In Stata, you can assign virtually any value to a local macro and in the simplest case, you designate the macro with local followed by the name given to the macro followed by the contents of the macro.  

local myvars age gender income sex

local text "The result of the test is "


In the first example, the macro name is myvars and in the second example, the macro name is text.  The first macro might be used as a shorthand way to specify a number of variables for several regression models whereas the second macro might be used if that particular string of text needs to accompany results slated for presentation (say, in a text file).   Not all macros, of course, are this simple or contrived (see Stata's help documentation or just search 'macro' on the Stata listserve to really have your mind blown).  A problem I recently encountered --- and one requiring a little research --- was how to assign a variable label to a macro.  Turns out, this is accomplished via the "extended macro functions" capability and, in retrospect, is somewhat straightforward.  The data attribute we want is the variable label and it is extracted with variable label..  Per the help documentation:

local macroname : variable label varname

You can then use the variable label by calling the local macro.  For a problem I was recently working on, I needed to recode several variables into new variables and instead of retyping the variable label from the original variables into the new variables (pure drudgery!), I wanted to automate the process via a foreach loop.   Below is an example .do file created solely to illustrate the concept (and to remind me how to do this in the future):

* **make 100 observations
set obs 100
* **create two variables, x & y, using random number generator functions
gen x = runiform()        // uniform
gen y = rnormal()        // normal
* **label the variables
label var x "Uniform Distribution"
label var y "Normal Distribution"
* **loop thru both variables and macro out both labels then display them
foreach var of varlist x y {
 local `var'lbl : variable label `var'
 display as text "The variable label of `var' is ``var'lbl'"
}
*end loop


The output from the foreach loop displays the text inside the double quotes as well as the variable names and labels, respectively:

The variable label of x is Uniform Distribution
The variable label of y is Normal Distribution

No comments:

Post a Comment