Use of embedded quotation marks within locals in Stata

Proper use of single and double quotation marks is essential when working in Stata, especially when writing loops where locals can be a huge time and memory saver. The use of single and double quotation marks is rather straightforward (using ` and ‘ for single, and ” for double quotation marks). You can rather easily define a local, e.g. based on the average of a variable

sum varname 
local mean_of_varname=`r(mean)'

Or if you simply want to store a string in the local, write

local new_string="This is a string local"

But what do you do if you want the local to also include a double quotation mark? This can be handy, for example if you want to store information in the local that can be used to be inserted in the definition of a figure. Suppose you want to store

1 "First variable label" 2 "Second variable label"

to be used in a figure for defining the legend. If you store

local local_for_legend "1 "First variable label" 2 "Second variable label""

Stata will interpret the inner quotation marks as delimiting quotation marks. To tell Stata that the inner quotation marks should be interpreted purely as characters, you have to embedd it in compound quotes:

`" characters_in_loop "'

(opening single – opening double – character of interest – closing double – closing single)

Or:

local local_for_legend `"1 "First variable label" 2 "Second variable label" "'

Leave a Reply