Assign value to local variable with if-statement

3.6k Views Asked by At

I'm trying to assign a conditional value to a local macro variable in Stata 15.

I have a local variable that only can have two values; "o" or "u". Then I have another local variable that I want to get the other letter of these two than the first local variable.

My code looks like this:

local utr o /*Can be assigned either "o" or "u".*/
local uin u if `utr' == o
local uin o if `utr' == u
di "utr = `utr'"
di "uin = `uin'"

I've also tried a number of variations of this code where I only have one "=" in the if statement and have had "" around the letters in the conditional statements.

I get a error messages that says:

if not allowed

so I guess I can´t do it like this if it´s possible at all.

Is it at all possible to assign "automated" conditional local variable values in Stata?

And if it is possible, how should I do this?

2

There are 2 best solutions below

1
On BEST ANSWER

Local macros are not variables; these two are distinct in Stata.

The following works for me:

local utr o // can be assigned either "o" or "u"

if "`utr'" == "o" local uin u 
else local uin o

display "utr = `utr'"
utr = o

display "uin = `uin'"
uin = u

See this page for an explanation on the difference between the if command and the if qualifier.

0
On

Let's focus on the if qualifier not being allowed in the definition of a local macro. This is a supplement to @Pearly Spencer's fine answer and not an alternative to it.

First off, the syntax diagram for the local command (e.g. help local gets you there) doesn't show that it's allowed. That almost always means that it really is forbidden. (Very occasionally, there are undocumented details to syntax.)

Second, and more to the point, there is no reason for an if qualifier here. An if qualifier allows for different results depending on a subset of observations, but local macros have nothing to do with the dataset strict sense. They apply equally to all observations or indeed to none.

None of that denies that a programmer, like you, often wants to define local macros conditional on something else, and that calls for something else, such as the if command or cond().