Announcement

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

  • Cannot pass global macros in "foreach"

    Hi, I'm working on a project that applies the same set of analysis to each of the fifty states. So, I want to automate the process, which doesn't seem complicated using STATA's built-in "foreach" loop. I setup a global macro, which are the abbrv.s of the state names. However, I'm having trouble pass the macro. My code looks like:

    * all files are in the working directory

    global states "CA DE ... "

    foreach state of global states {
    use ${state}xxx.dta, clear

    do dofilename1.do
    do dofilename2.do
    ...
    }

    Stata didn't seem to recognize "${state}". I couldn't even open the data file in the main script. If I instead used `state' (the single-quotation for a local macro), Stata would read and open the data file. However, I couldn't pass the macro `state' to the following do files (since it's "local"). I swear to god the above code worked at some point. Then, it failed for no reason. I'm using Stata 11. How can I resolve this issue. I've been struggling on this and trying to find a solution for a whole day, but no luck. Really appreciate your help!!!

  • #2
    The foreach command you've issued automatically creates a local macro, state. This is why your use statement opens the file when you specify the local macro but does not when you specify the global macro. This is expected behavior.

    You have two options for dealing with this.

    The best option is probably to use include instead of do to call the dofiles. When doing so the dofiles will be run as part of the same session and thus have access to the local macros.

    The other option is to add the following line at the beginning of the loop:
    global state `state'

    Comment


    • #3
      Same question, and similar answer, within http://www.statalist.org/forums/foru...cro-in-foreach

      In fact, the other answer gives a third option....

      Comment


      • #4
        Thank you so much, folks! I think your comments should be included in Stata manual.

        Comment

        Working...
        X