statastata-macros

Loop over a different set of control variables in stata


I am trying to loop over a different set of control variables. I run the below code but get an error { required. Any help would be appreciated.

local tmax "tmax_3 tmax_2 tmax_1 tmax0 tmax1 tmax2 tmax3"
local tmin "tmin_3 tmin_2 tmin_1 tmin0 tmin1 tmin2 tmin3"
local precip "precip_3 precip_2 precip_1 precip0 precip1 precip2 precip3"

est clear
local m=1
foreach var of varlist good_health better_health {
    foreach weather of local tmax tmin precip {
        eststo model_`m'_`weather': reg `var' `weather', robust cluster(parish_id)
        local m `++m'
    }
}

Solution

  • When using syntax of local in foreach Stata expects only one local. So after the first local Stata expects a {. But you have a second and a third local before the {. You should be able to solve this using in in foreach where Stata first interprets your three locals, then iterate over all items in each of them. See below.

    local tmax "tmax_3 tmax_2 tmax_1 tmax0 tmax1 tmax2 tmax3"
    local tmin "tmin_3 tmin_2 tmin_1 tmin0 tmin1 tmin2 tmin3"
    local precip "precip_3 precip_2 precip_1 precip0 precip1 precip2 precip3"
    
    est clear
    local m=1
    foreach var of varlist good_health better_health {
        foreach weather in tmax tmin precip {
            eststo model_`m'_`weather': reg `var' ``weather'', robust cluster(parish_id)
            local m `++m'
        }
    }
    

    Edit: Now you are only iterating over the names of the local. ``weather'' is now a nested local, where it first gets the name that the local `weather' points to, then it interprets that local and gets your variable list.