Loop multiple locals

289 views Asked by At

I have the auto dataset and would like to create a few bar graphs:

    sysuse auto, clear
        local mpg "22 20 17"
        local titles "Title1 Title2 Title3"
        local path "twentytwo twenty seventeen"

 foreach x of local mpg {
 foreach y of local titles {
 foreach z of local path {
            keep if mpg==`x' & foreign==0
            egen hv_rank=rank(price)
        # delimit ;
        graph bar price,
            over (make, sort(hv_rank) reverse label(labsize(vsmall)))
            ytitle("")
            horizontal title("`y'", size(medium))
            ;
        # delimit cr
            graph save "$dir_gphs\mpg`z'f0-bal.gph", replace
            drop hv_rank
            sysuse auto, clear
            }
           }
          }

I do not want to create a bar chart for every possible combination of the "values" of my 3 locals but instead I´d like to have if x=22, then y=Title1 and then z=twentytwo. Likewise if x=20 then y=Title2 and z=twenty.

This must be a simple problem. And I guess my search so far has not brought me any usable results because I do not know the right vocabulary of the problem.

2

There are 2 answers

3
AudioBubble On BEST ANSWER

Here is how I would approach the problem.

. local mpg 22 20 17

. local titles `" "Title 1" "Title 2" "Title 3" "'

. local path twentytwo twenty seventeen

. 
. forvalues i = 1/3 {
  2.         local x : word `i' of `mpg'
  3.         local y : word `i' of `titles'
  4.         local z : word `i' of `path'
  5.         display `" `x' --- `y' --- `z' "'
  6.         }
 22 --- Title 1 --- twentytwo 
 20 --- Title 2 --- twenty 
 17 --- Title 3 --- seventeen 

Or alternatively

. local set1 22 "Title 1" twentytwo

. local set2 20 "Title 2" twenty

. local set3 17 "Title 3" seventeen

. forvalues i = 1/3 {
  2.         local x : word 1 of `set`i''
  3.         local y : word 2 of `set`i''
  4.         local z : word 3 of `set`i''
  5.         display `" `x' --- `y' --- `z' "'
  6.         }
 22 --- Title 1 --- twentytwo 
 20 --- Title 2 --- twenty 
 17 --- Title 3 --- seventeen 
0
Nick Cox On

As you say, you really want a single loop. Realising that depends on experience rather than finding some documentation.

I can't test this because it hinges on your local directory structure and a global macro that is not defined, so your example is not reproducible. I have made some incidental simplifications.

If your individual elements contained spaces, you would need double quotes to bind.

sysuse auto, clear

forval j = 1/3 
    local x : word `j' of 22 20 17
    local title: word `j' of Title1 Title2 Title3
    local path: word `j' of twentytwo twenty seventeen 

    graph bar price if mpg==`x' & foreign==0   ///
    over(make, sort(1) reverse label(labsize(vsmall))) ///
    ytitle("") horizontal title("`title'", size(medium)) 

    graph save "$dir_gphs\mpg`path'f0-bal.gph", replace
}