0
votes

I have a situation where I need to use values in two variables mpg and make to create a graph. The variable mpg is a numerical variable and make is a string variable with spaces. The following code is able to use the values in mpg to create the graph when I ignore the values in the make variable. However I would like to have the corresponding string value from variable make appear in the graph subtitle. For some reason this code gives the error too many ')' or ']' after looping over several of the values in the variable mpg

sysuse auto.dta, clear

gsort - trunk
keep in 1/5

levelsof mpg, local(levels)
global xlist  `levels'
levelsof make, local(levelsdes)
global ylist `levelsdes'

sysuse auto.dta, clear
gen bar=1
local k 1 2 3 4 5  
local n : word count $xlist
forvalues x =1/`n' {
local i : word `x' of $xlist
local z : word `x' of `k'
local j : word `x' of $ylist

egen a_`i'= total(bar) if mpg == `i'

twoway (bar a_`i' mpg ), subtitle(`j') title(Trends in Error `i') 
graph export "`z'.png", as(png)  replace
}
1
Add display ā€œ-- `i’ -- `j' -- `z’ --ā€ into your loop and you will see the beginnings of your problem. - user4690969

1 Answers

1
votes

The issue here is wanting to use a particular string value from a variable in a graph title. Putting string values into a macro using levelsof and then pulling them out again is (1) indirect and (2) tricky, as spaces complicate any extraction based on words. So, it seems to me that you can and should do this more directly:

sysuse auto.dta, clear
gsort - trunk
gen bar = 1

forval i = 1/5 { 
    egen a_`i'= total(bar) in `i'
    twoway bar a_`i' mpg, subtitle("`=make[`i']'") 
    graph export "`i'.png", as(png)  replace
}

There will be something equivalent for your real problem, even if string values refer to subsets of observations that aren't singletons, but to get more detailed advice you should explain more about the real problem.

Note incidentally that

local k 1 2 3 4 5  

forvalues x = 1/5 {
    local z : word `x' of `k'
}

is also indirect. Your loop is set up to cycle over 1/5, so you don't need to do that twice. Defining k and then extracting its members in sequence can be avoided by just referencing the local macro x.