1

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'
}
Nathan
  • 23
  • 4
  • Although what you are talking about would be called a variable in many languages, in Stata it is customarily called a local macro, and not a local variable. A Stata variable is (only) a variable (meaning, field or column) in the dataset. (Mata is a different story, but, other way round, it has itself no concept of local macros.) – Nick Cox Oct 15 '20 at 16:00

1 Answers1

1

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

Nick Cox
  • 35,529
  • 6
  • 31
  • 47
  • Thank you very much that seems to work. I simplified the problem so that you could find the solution quicker so I the DDM actually is necessary. – Nathan Oct 15 '20 at 16:03
  • If the real problem is different a (good) answer could be different too, but you would have to tell us about that. – Nick Cox Oct 15 '20 at 16:05