Search code examples
loopsstatalocals

Loop multiple locals


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.


Solution

  • 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