Search code examples
variablesstatalocalstata-macros

How do I use a local macro referencing a variable?


I am trying to create a macro in Stata that will set a variable name for me to reference later on in my do file. Essentially, I am trying to replace a variable name with a local macro.

An example dataset is the following:

ID   Indicator1 Indicator2    Amount
1    1            0             10
2    0            1             2
3    0            0             3
4    1            0             5
5    1            1             20

My data has a number of indicators but I only have to work with only one indicator at a time. I want to put the indicator that I'm currently working with into a macro, so that I have to change only one thing in my entire code.

My code is:

local myvar = "Indicator"

What I want is to be able to use something like this:

sum Amount if "`myvar'" == 1

However, I keep getting an error that says "type mismatch" even though myvar has been defined.


Solution

  • By typing any of these

    local myvar "Indicator" 
    

    or

    local myvar = "Indicator" 
    

    or

    local myvar Indicator 
    

    you place the literal text Indicator inside a local macro with the name myvar. The " " in this example are delimiters and, as the last example shows, dispensable in this case. So far, so good.

    However, the use of " " in your summarize statement indicates to Stata that you intend the result of evaluating (dereferencing) the local macro to be treated as a literal string; and a literal string can only be compared with another literal string or the contents of a string variable, indicated by its name. Hence the error message type mismatch.

    So, this would be legal:

    sum Amount if "`myvar'" == "1"
    

    Nothing would happen, because "indicator" is not equal to "1", so the statement would be false (in every observation for which it was tried). But Stata would have no problem with the syntax.

    But it is not what you want. You want the local macro contents to be treated as a variable name, which means writing

    sum Amount if `myvar' == 1 
    

    The fact that the local macro has been defined is immaterial here; it is being used improperly.