foreach - Loop through list of values in table -
i have stata code starts with:
local mystate "[state abbreviation]"
the user enters state abbreviation (e.g., "fl"
) , runs code. rest of code references mystate
multiple times. example:
keep if stateabb == `"`mystate'"' replace goal = .95 if stateabb == `"`mystate'"' save "results `mystate'.dta", replace if (stateabb == `"`mystate'"' & pickone==1) using ...
i have list of 10 or states need code run. it's saved in table, called "statestorun.dta,"
1 variable name, "state"
.
is there way edit code loops through each state in table, , runs full code each state?
i've studied foreach
, forval
examples cannot figure out how or if apply situation. suggestions?
foreach
can take local macro list of states want loop through. missing piece creating list. so, can use levelsof
local
option on "statestorun" dataset (not '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 `mystate'.dta", replace if (stateabb == `"`mystate'"' & pickone==1) using ... }
postscript
however, unless generating "statestorun.dta" stata do-file, seems may easier define list of states directly in analysis do-file. same basic method can 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 `mystate'.dta", replace if (stateabb == `"`mystate'"' & pickone==1) using ... }
if want define statelist
, use across multiple analysis do-files, see help include
(note difference between include
, do
): can define statelist
in separate do-file , include
it, rather creating stata dataset single variable sole purpose of looping on distinct values of variable.
Comments
Post a Comment