Announcement

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

  • help with foreach var of local varlist

    Hi all,

    I am trying to do some code over a selection of variables in a dataset. So i wanted to create a local variable with all variables, and then loop over all varialbes by calling up that local. But it doesn't work. any suggestions?

    Thanks, Sandra

    des _begin-_end, varlist
    return list varlist

    foreach var of local varlist{
    di `var'
    }


  • #2
    On expressions like "it does't work" please see FAQ 12.

    You never define local macro varlist, this is why there are zero elements to loop over.

    Probably you want

    Code:
    foreach var of varlist _begin-_end {
    
    }
    Best
    Daniel

    Comment


    • #3
      Hi Sandra,

      you can also do it the way you described, but you have to copy the return value of describe, varlist into a local (named 'vars' in syntax below), and then use that local in the foreach-loop
      Code:
      quietly describe _begin - _end, varlist
      local vars = r(varlist)
      foreach x of varlist `vars' {
          display " `x' "
      }
      Greetings, Klaudia

      Comment


      • #4
        Hi Sandra,

        you can also do it the way you headed for, but you have to copy the return value of describe, varlist into a local (named 'vars' in syntax below), and then use that local in the foreach-loop
        Code:
        quietly describe _begin - _end, varlist
        local vars = r(varlist)
        foreach x of varlist `vars' {
            display " `x' "
        }
        Greetings, Klaudia

        Comment


        • #5
          While there is nothing wrong with the basic approach, the line

          Code:
          local vars = r(varlist)
          can be dangerous, especially in older Stata versions (see Cox, 2008). Coding

          Code:
          local vars `r(varlist)'
          is safer. Also see ds, and unab for such approaches.

          Best
          Daniel


          Cox, N.J. (2008). Stata tip 70: Beware the evaluating equal sign. The Stata Journal, 8(4): pp. 586–587.

          Comment


          • #6
            many thanks!

            Comment

            Working...
            X