1

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.

Kany
  • 39
  • 7

1 Answers1

3

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.

Nick Cox
  • 35,529
  • 6
  • 31
  • 47
  • Thank you. I tried using sum Amount if ``myvar' == 1` and the error this time says `==1 invalid name` even though it has been defined. – Kany Mar 28 '17 at 22:32
  • 1
    That probably means that the local macro is not visible at that point. That is a common side-effect of running a do-file in chunks, e.g. a line at a time. Local means what it says: local (to a chunk of code). To test, try to display the macro before you try to use it: `macro list` will do that or `di "\`myvar'"`. The remedy is not to run the file in chunks or in any case to ensure that the `local` definition is visible. – Nick Cox Mar 28 '17 at 22:39
  • Oh okay. The problem is I was running the do-file in chunks. It works now. :) – Kany Mar 28 '17 at 22:48