Announcement

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

  • Cannot pass global macro 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 key here is although you defined a global called states, the entity state used in your loop is local to the loop and not global at all. So the only logical syntax is

    Code:
    foreach state of global states {
    use `state'xxx.dta, clear
    
    }
    To pass each name to the do-file, pass it as an argument

    Code:
    do filename1 `state'
    and at the top of each do-file have a definition something like

    Code:
    local state `1'
    and refer to that local within the do-file.

    Despite your fervour, I don't believe that your code as cited here ever worked, because what is true now was always true. I can't comment on anything you tried but did not report.

    Comment

    Working...
    X