Search code examples
loopsforeachsyntax-errorhistogramstata

Introduction to local macros and foreach loops not replicable?


I’m doing a Stata tutorial to try and catch up on macros, loops and data visualization. I tried replicating the syntax patterns from different tutorials using my own data, and Stata insists that the syntax is incorrect (even when it’s identical save for the variable names). It displays nothing for the local macro, and then the foreach command generates endless "not allowed" errors. I am now really confused.

I would like to, ideally, create a macro that substitutes for a set of variables, and create a loop that generates (and saves) tailored histograms for each variable in that macro.

Can someone please identify why the following syntax is invalid?

I’ve included my current iteration, and a copy of the tutorial syntax. I was wondering if maybe the tutorial has downloaded something that permits this particular syntax (Youtube's "Anatomy of a loop in Stata using foreach" video by Stata Analysis101). I've dropped them a note, but in the meantime...

anyone?

Current iteration (run from .do file):

local caseloadA_5 avVFTE_total_5 avVPTE_total_5 PEcaseloadA_5 PEcaseloadB_5 PTPEcaseloadC_5
foreach var of varlist `caseloadA_5' {

histogram `var', ///
bin(40) start(0) ///
percent ///
addplot(fcolor(green%60) lcolor(black%70)) ///
ytitle("Affiliates") ///
xtitle("`var'") ///
legend(off) ///
subtitle("2021-2022: `var'") ///
saving("\\STLFS01\Public\Tatiana Gochez-Kerr\Task - APR\Annual APR\Annual APR 2021-2022\`var'.gph", replace)
}

sample errors:

barw(0.9) is not a twoway plot type
r(198);
fcolor(green%60) is not a twoway plot type
r(198);
option kdenopts() not allowed
r(198);
option ytitle() not allowed
r(198);
option xtitle() not allowed
r(198);
option legend() not allowed
r(198);
option saving() not allowed
r(198);

Tutorial syntax:

local x size_cat status death_percent

foreach y of varlist `x' {
histogram `y', ///
percent ///
color(erose%45) ///
ylabel(, valuelabel) ///
xtitle("`y'") ///
subtitle("Histograms for aggregate hospital data 2012") ///
graphregion(color(white))
saving("$pp/graphres/`y'", replace)
}

Solution

  • This works for me using a do-file.

    sysuse auto, clear 
    
    foreach y in price mpg weight { 
        
    histogram `y', ///
    percent ///
    color(erose%45) ///
    ylabel(, valuelabel) ///
    xtitle("`y'") ///
    subtitle("Histograms for auto data") ///
    graphregion(color(white)) ///
    saving("`y'", replace)
    
    }
    

    It's a matter of style not syntax, but the tutorial's foreach syntax is more indirect than it needs to be.

    If you want to put a list of variable names in a local macro as in

    local myvars price mpg weight 
    

    then you can follow with

    foreach y of local myvars {