Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • loop over subset of variable list

    Hi,

    I want to execute a code for a list of variables, and part of the code only for a subset of the list (varA and varB)

    I found an unelegant way to do this using an indicator `i', see below.
    Does anyone know how I can directly use the positions of varA and varB in the local list?

    * execute code1 for all variables ; execute code2 for varA and varB

    local varlist var1 var2 varA varB var3
    local i 0
    foreach var of local varlist {
    local i = `i' + 1
    di "step `i' code1 "
    if inlist(`i',3,4) {
    di "code2 for `var'"
    }
    }

    Last edited by Karen Geurts; 26 Feb 2017, 08:10.

  • #2
    There is no good advice independent of the details you don't show. For example, sometimes two separate loops make sense, one over some of the variables and one over the others.

    But this may be closer to what you want. The key advice here is that as your loop is over variable names, a counter is just an unnecessary complication.

    Code:
    local varlist var1 var2 varA varB var3
    
    foreach var of local varlist {
    
        if inlist("`var'", "varA", "varB")  {
            ....
       }
    
    }

    Comment


    • #3
      Thank you Nick, this answers my question.
      I tried this, but without double quotation marks. That is the key.
      Karen

      Comment

      Working...
      X