0
votes

I am working with Stata. I have a variable called graduate_secondary. I generate a global variable called outcome, because eventually I will use another outcome. Now I want to replace the variable graduate if a condition relative to global is met, but I get an error:

My code is:

global outcome "graduate_secondary"

gen graduate=.

replace graduate=1 if graduate_primary==1 & `outcome'==1

But i receive the symbol ==1 invalid name. Does anyone know why?

2
Although global macros can be used like variables in other software, in Stata they are customarily called that, not global variables. stata.com/statalist/archive/2008-08/msg01258.html said more.Nick Cox
I recommend not using Stata, try learning other languages like Pyhton or R which are open source and substantially more popular.cach dies

2 Answers

2
votes

Something along those lines might work (using a reproducible example):

sysuse auto, clear        
global outcome "rep78"

gen graduate=.

replace graduate=1 if mpg==22 & $outcome==3
(2 real changes made)

In your example, just use

replace graduate=1 if graduate_primary==1 & $outcome==1  

would work.

2
votes

Another solution is to replace global outcome "graduate_secondary" with local outcome "graduate_secondary".

Stata has two types of macros: global, which are accessed with a $, and local, which are accessed with single quotes `' around the name -- as you did in your original code.

You get an error message because a local by the name of outcome has no value assigned to it in your workspace. By design, this will not itself produce an error but instead will the reference to the macro will evaluate as a blank value. You can see the result of evaluating macro references when you type them by using display as follows. You can also see all of the macros in your workspace with macro dir (the locals start with an underscore):

display `outcome'
display $outcome

Here is a blog post about using macros in Stata. In general, I only use global macros when I have to pass something between multiple routines, but this seems like a good use case for locals.