Search code examples
if-statementstatastata-macros

Assign value to local variable with if-statement


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?


Solution

  • 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.