2
votes

I'm trying to figure out a way of delimiting elements of a local macro so that I can reference each element by their position in the macro. For example in the local macro list_1 below, by adding `" "' around the whole list and including "" around each element, Stata will recognize that "item 1" is the first element in the list and "item 2" the second element and so on.

loc list_1 `" "item 1" "item 2" "item 3" "'
loc n: word count `list_1'
forval i=1/`n' {
  loc element `: word `i' of `list_1''
}

However, when you have list of elements contain "", as in the example below, Stata will not recognize those as a single element.

loc list_1 `" "inlist(var1,"a","b","c")" "inlist(var1,"e","f","g")" "'

What I would like is for Stata to recognize inlist(var1,"a","b","c") as the first element and inlist(var1,"e","f","g") as the second element in the list. Any ideas on how I maybe able to achieve that?

2
Compound double quotes must be left single quote - double quote at start and double quote - right single quote at end. Your last line of code has it the wrong way round, which means nothing special to Stata. NB not STATA. - Nick Cox
Sorry - that was a type. I've made the correction above - user4816715

2 Answers

2
votes

All but the innermost double-quotes must be compound, I believe. The following

local list_1 `" `"inlist(var1,"a","b","c")"' `"inlist(var1,"e","f","g")"' "'

foreach word of local list_1 {
    display `"=== `word' ==="'
    }

yields

=== inlist(var1,"a","b","c") ===
=== inlist(var1,"e","f","g") ===
2
votes

Compound double quotes starting and ending:

loc list_1 `"inlist(var1,"a","b","c") inlist(var1,"e","f","g")"'

forval i = 1/2 {
  display `"`:word `i' of `list_1''"'
}

// or

foreach word of local list_1 {
    display `"`word'"'
}

If you use

loc list_1 `" "inlist(var1,"a","b","c")" "inlist(var1,"e","f","g")" "'

the compound quotes will later be stripped, leading to four pieces identified as

inlist(var1,
a","b","c")"
inlist(var1,
e","f","g")"

The latter and

loc list_1 "inlist(var1,"a","b","c")" "inlist(var1,"e","f","g")"

lead to the same undesired result with your example. Stata is doing the best it can, given your setup.

Notice that even this works for you:

loc list_1 inlist(var1,"a","b","c") inlist(var1,"e","f","g")