Search code examples
statastata-macros

Stata if condition within a loop


I am trying to write a loop with a macro variable that will change depending on the iterated value of the loop. See the code below.

I want to loop over ticker values "QLD" and "DDM" and i want the local macro index to equal "QQQ" if the ticker is "QLD" otherwise "DIA."

foreach ticker in "QLD" "DDM"{
    if `ticker'="QLD"{
        local index = "QQQ"
    }
    else{
        local index = "DIA"
    }
    di `index'
}

Solution

  • The code you ask for is more nearly

    foreach ticker in QLD DDM {
        if "`ticker'" == "QLD" local index = "QQQ"
        else local index = "DIA"
        
        di "`index'"
    }
    

    There are two errors in your code and some more code than you need. The errors are omitting quotation marks where needed and using = to test equality.

    This choice alone doesn't need a loop:

       local index = cond("`ticker'" == "QLD", "QQQ", "DIA") 
       di "`index'" 
    

    In fact as the command above shows, DDM doesn't obviously need to be mentioned at all. (If it does, then your code is wrong for some other reason.)