Announcement

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

  • Looping over previously defined code

    Hello!

    I´m programming several combinations of regressions. In order to streamline the code and avoid unnecessary work when changes to the regressions are need, I decided to define the regression models inside programs, and then call the necessary program using if and else statements inside the loops. My problem comes from Stata not executing the code inside the program as I expected. I made the following very simplified example to demonstrate what I would expect to happen:

    Code:
    capture program drop myprog1
    program define myprog1
        di "var is: `size'"
    end
    
    local vars all size_class
    foreach myvars of local vars {
        myprog1
        
    }
    Thus, I expected that in the first and second time the loop runs, the output to be:

    Code:
    var is: all
    var is: size_class
    But what I get is:

    Code:
    var is:
    var is:
    I appreciate any insights on how I can make this work or if you can link me to any guides that addresses this problem or other solutions regarding loops over loops or loops with programs.

    Thanks for your help!
    Best,
    Hélder

  • #2
    Loops are not at the core of the described behavior here. Programs have their private namespace. The local macros you define outside of programs are not visible within the programs -- unless you pass them as arguments. Here is an even more minimalistic example:

    Code:
    program foo
        
        display "foo: `foo'" // <- does not show anything
        
        args foo // <- assign the first argument to local foo
        
        display "foo: `foo'"
        
    end
    
    local foo bar
    foo `foo'
    which yields

    Code:
    (output omitted)
    . foo `foo'
    foo:
    foo: bar
    Here is your example revised:

    Code:
    capture program drop myprog1
    program define myprog1
        
        args size // <- new
        
        di "var is: `size'"
    end
    
    local vars all size_class
    foreach myvars of local vars {
        myprog1 `myvars' // <- modified
        
    }
    producing the desired output.
    Last edited by daniel klein; 22 Dec 2023, 04:18.

    Comment


    • #3
      Thank you Daniel Klein, your solution worked!

      Comment

      Working...
      X