Stata if condition within a loop

2.7k views Asked by At

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'
}
1

There are 1 answers

2
Nick Cox On BEST ANSWER

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