Larry
Larry

Reputation: 183

Loop through list of values in table

I have Stata code that starts with:

local MyState "[STATE ABBREVIATION]"

The user enters the state abbreviation (e.g., "FL") and then runs the code. The rest of the code references MyState multiple times. For example:

keep if stateabb == `"`MyState'"' 
replace Goal = .95 if stateabb == `"`MyState'"'
save "Results for `MyState'.dta", replace
if (stateabb == `"`MyState'"' & pickone==1) using ... 

I often have a list of 10 or so states for which I need this code run. It's saved in a table, called "StatesToRun.dta," with one variable name, "state".

Is there a way to edit my code so it loops through each state in my table, and runs the full code for each state?

I've studied the foreach and forval examples but cannot figure out how or if they would apply to this situation. Any suggestions?

Upvotes: 0

Views: 310

Answers (1)

Brendan
Brendan

Reputation: 4011

foreach can take a local macro with a list of the states you want to loop through. The missing piece is actually creating this list. To do so, you can use levelsof with the local option on your "StatesToRun" dataset (not a 'table' in Stata terminology). E.g. (without testing):

use StatesToRun.dta, clear
levelsof state, local(statelist)

use data, clear
foreach MyState of local statelist {
    keep if stateabb == `"`MyState'"' 
    replace Goal = .95 if stateabb == `"`MyState'"'
    save "Results for `MyState'.dta", replace
    if (stateabb == `"`MyState'"' & pickone==1) using ... 
}

Postscript

However, unless you are generating "StatesToRun.dta" from another Stata do-file, it seems like it may be easier to simply define the list of states directly in the analysis do-file. The same basic method can be used:

local statelist MA NH VT ME CT RI PA NY 

use data, clear
foreach MyState of local statelist {
    keep if stateabb == `"`MyState'"' 
    replace Goal = .95 if stateabb == `"`MyState'"'
    save "Results for `MyState'.dta", replace
    if (stateabb == `"`MyState'"' & pickone==1) using ... 
}

If you want to define statelist and use it across multiple analysis do-files, see help include (note the difference between include and do): you can define statelist in a separate do-file and include it, rather than creating a Stata dataset with a single variable for the sole purpose of looping over the distinct values of this variable.

Upvotes: 1

Related Questions