Home > Back-end >  Loop over a do file with regression model in Stata
Loop over a do file with regression model in Stata

Time:08-05

I am estimating several regressions in Stata with the same functional form. I'd like to perform my estimations by looping over a .do file that contains the "program" for my regression. The (simplified) code I have attempted is as follows:

local vars waz haz whz cough fever diar

foreach depvar of local vars {
forvalues i = 10(5)15 {

do "Regression.do"

}
}

Where "Regression.do" is this code:

reg `depvar' distance_`i'
est store `depvar'_`i'

Stata returns an error message: "Error: last estimates not found." How can I amend my code so that I can execute the .do file in a loop?

CodePudding user response:

Simplifying your code as suggested by @Nick Cox is best, however, to answer your question the solution is below:

main do-file

local vars waz haz whz cough fever diar

foreach depvar of local vars {
forvalues i = 10(5)15 {

do "Regression.do" "`i'"

}
}

regression.do

reg `depvar' distance_`1'
est store `depvar'_`1'

CodePudding user response:

The do-file here is hardly needed, so using its contents directly avoids the problem that local macros are ... local ... meaning only visible within the same program space.

foreach depvar in waz haz whz cough fever diar { 
    foreach num in 10 15 { 
        reg `depvar' distance_`num'
        est store `depvar'_`num'
    }
}

is one way to simplify your code. although that is partly a matter of taste.

See also https://journals.sagepub.com/doi/pdf/10.1177/1536867X20931028 for more on what bit you.

You do flag that you have fuller code, which is fair enough, and at some point having a do-file and passing arguments to it may appear to be better style.

Conversely, I see a lot of Stata code which puts content into a local macro only to take it out again just once and immediately. This is like "I have a pen. I put it in a box. I take it out of the box. I now have my pen again." Sometimes the box (meaning, local macro) is a good idea; but other times there is no gain to writing the code that way.

  • Related