Announcement

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

  • Referencing a local with another local inside of it

    I am trying to run a regression loop that loops over different treatment variables and if conditions based on the treatment variable, but am running into what I think is a syntax issue with my code.

    Please see a (trivial) example that illustrates the problem below.


    Code:
    * Load data
    sysuse auto, clear
    
    * Set up local for treatment variables
    local trt_var_list mpg headroom trunk
    
    * Set up local for condition list
    local cond1 "if foreign != ."
    local cond2 "if `trt' > 3"
    
    *** Run analysis loop
    * Loop over treatments
    foreach trt in `trt_var_list' {
        
        * Loop over if conditions
        forvalues i=1/2 {
            
            * Run regression
            reg price `trt' `cond`i''
            
        }
        
    }
    The code stops after one regression, giving the error message: ">3 invalid name; r(198)".





    Any help on this would be much appreciated!

  • #2
    You need to escape the macro expansion of trt when defining macro cond2.
    Code:
    clear all
    
    * Load data
    sysuse auto, clear
    
    * Set up local for treatment variables
    local trt_var_list mpg headroom trunk
    
    * Set up local for condition list
    local cond1 "if foreign != ."
    local cond2 "if \`trt' > 3"      // notice backslash before `trt'
    
    *** Run analysis loop
    * Loop over treatments
    foreach trt in `trt_var_list' {
    
        * Loop over if conditions
        forvalues i=1/2 {
    
            * Run regression
            reg price `trt' `cond`i''
    
        }
    
    }

    Comment


    • #3
      Your definition of local cond2 is premature. Local trt is not yet defined when you defined it. It's not an error to refer to a local macro that doesn't exist (yet), but Stata evaluates the reference as an empty string. There is no placeholder for an undefined macro to be filled in later.

      A good way to debug problems like this is to display local macros to check what they contain.

      Typing mac list is a shotgun approach.

      This should be closer to what you want.

      Code:
      foreach trt in `trt_var_list' {    
           local cond2 "if `trt' > 3"

      Comment

      Working...
      X