Announcement

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

  • Drop macro in a loop

    Dear Experts,

    I have a piece of code , where a local multiplier is generated in a loop and is suppoesed to be dropped at the end of each cycle of local Seq.
    A new local multiplier should be defined for each n of local Seq.

    Code:
    su groups_`i', meanonly
              forvalues k = 1/`r(max)' {          
    
     levelsof min_Sequence_num if groups_`i' == `k', local(Seq)
                
                foreach n of local Seq {
                    
                    local t : label min_Sequence `n'
                    display "`t'"
                    
                    foreach var of global var_of_interest {
                        
                        quietly: summarize `var'_sub_var if groups_`i' == `k' & min_Sequence_num == `n'
                            
                            local `var'_gr = r(mean) + 1
                            
                            if (``var'_gr' == .) local `var'_gr = 1
                            if (``var'_gr' == 0) local `var'_gr = 1
                            
                            local multiplier = "`multiplier'" + "*" + "``var'_gr'"
                            di "`multiplier'"
                    }
                    
                        local multiplier = substr("`multiplier'", 2, .)
                
                        local b1_x1 = `b_x1' * `multiplier'
                        local b1_x2 = `b_x2' * `multiplier'
                        
                        macro drop multiplier
     }
     }
    This code works, but local multiplier seems not to be dropped at the end. It runs correctly for the first n of local Seq, but for the next n it adds to the local multiplier from the previous n.

    Any advice is very much appreciated.

    Sincerely,

    Pavlo

  • #2
    You need
    Code:
    macro drop _multiplier
    Without the preceding underscore, it would drop a global macro named multiplier

    Comment


    • #3
      Sure it does, as you have defined multiplier using multiplier in the first run. multiplier will have no value in the first run, but will in subsequent runs.

      Not sure the macro drop resolves that problem in the first loop.

      Comment


      • #4
        Worked like charm, thanks

        Comment


        • #5
          It's a question of style, but many Stata programmers would blank out the macro at the outset each time round the loop, and


          Code:
          local multiplier
          does that. There is a nuance between the macro no longer existing and it being empty, but the effect is the same either way.

          Comment

          Working...
          X