Announcement

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

  • using macro variables in loop

    Dear all,

    I am writing to ask for help in using macro variables in loops.

    My code is something as follows. The reason I define a global ind_var is that I want to use different sets of ind_var so that I can just uncomment one of them and comment the rest to reuse the program.

    However it does not seem to work - stata seems to ignore `type' in the regression.

    Anyone know how to get this to work? or is it not possible to use macro variables in loop? Any advice or comment is highly appreciated.

    global controls control1 control2 control3
    global ind_var iv1`type' iv2`type' iv3`type' iv4`type'
    *global ind_var iv1`type' iv2`type' iv3`type'
    *global ind_var iv1`type' iv2`type' iv5`type'
    *global ind_var iv1`type' iv2`type' iv6`type'

    foreach type in type1 type2 type3 type4{
    reg dv $ind_var $controls, fe
    }



  • #2
    Stata is ignoring the `type' dereferencing, because the local type is not defined.

    Define the type as a global, and dereference it as a global.

    Comment


    • #3
      Don't use globals unless you have to. Search the forum for the dangers of global macros. You can also append a suffix on the go:

      Code:
      local ind_var iv1 iv2 iv3 iv4
      foreach type in type1 type2 type3 type4{
          local reg_ind_var: subinstr local ind_var " " "`type' ", all  
          reg dv `reg_ind_var'`type' `controls', fe
      }
      Last edited by Andrew Musau; 01 May 2021, 05:33.

      Comment


      • #4
        Code:
        foreach type in type1 type2 type3 type4 {
        
              reg dv $ind_var $controls, fe
        }
        The local macro type is never invoked inside the loop. So, this is legal but will just execute the same regression 4 times. The earlier code


        Code:
        global ind_var iv1`type' iv2`type' iv3`type' iv4`type'
        is no different from

        Code:
        global ind_var iv1  iv2 iv3 iv4
        unless the local macro type has been defined previous to that.

        Comment


        • #5
          Thank you so much for all your kind replies.

          Andrew's code worked. Thanks a million!!!

          Comment

          Working...
          X