1

I would like to create multiple graphs and combine them using a loop. I used the following code:

local var Connecticut Delaware Minnesota Missouri Rhode Island Tennessee Vermont Wisconsin Hawaii
local n: word count `var'
forvalues i=1/`n'{
local a: word `i' of `var'
line prop_report_agencies modate if statename=="`a'" , ytitle(proportion_agency reports for `a') saving(gg`a',replace)
local gg `gg' "gg`a'"
}
local gg: subinstr local gg "gg`a'" `""gg`a'""'

gr combine `gg'
graph drop _all

When I do this I get this error

ggConnecticut is not a memory graph

The first part of the code seems to work: the code creates graphs individually and stores them; however, it cannot combine due to an error.

Nick Cox
  • 35,529
  • 6
  • 31
  • 47
rrodrigorn0
  • 175
  • 3
  • 14

1 Answers1

1

First of all, let's correct the code, while also shrinking it from a meandering stream to a straight line:

local S Connecticut Delaware Minnesota Missouri "Rhode Island" Tennessee Vermont Wisconsin Hawaii
foreach s of local S { 
    line prop_report_agencies modate if statename=="`s'", ytitle(proportion_agency reports for `s') saving(gg`s',replace)
    local gg `"`gg' "gg`s'""' 
}

gr combine `gg'

In passing, note that you had a bug as Rhode Island is one state, but two words.

Your major problem, however, I guess, is that there is a conflict between the role of " " as string delimiters and the fact you need them as literal characters in the combine call. To stop the " " being stripped you need to use compound double quotes. Your code shows that you know about them. Compound double quotes are

`"  "' 

This example is dopey but nevertheless reproducible by Stata users using any recent version of Stata.

sysuse census, clear 

local S Alabama "Rhode Island" 
foreach s of local S { 
    histogram medage if state == "`s'", saving("gg`s'", replace) 
    local gg `"`gg' "gg`s'""'   
}

graph combine `gg'  

In future, use

macro list 

in your debugging to see what the problem is. My guess is that " " are missing from around Connecticut but present for other states.

To see the heart of the problem, consider the results of

local foo "bar"
mac li 

The local macro foo does not include the quotation marks, as they have been stripped. To insist on them, protect them with compound double quotes.

local foo `""bar"' 
mac li 
Nick Cox
  • 35,529
  • 6
  • 31
  • 47