For some reason I spent a lot of time yesterday doing this: turn a list of variables into a list with doublequotes for each variable, then separated by commas. I confess I still do not really understand the logic of Stata quotes… and numerous websites suggest they are indeed thinks to be wary of… Anyway, the reason I did this is because I then wanted to pass ttpcomma into an inlist function, but I could never get it to work (and no, it did not exceed the 10 string variables). The inlist would not “read” the local, even though it would when I created what I thought was the exact same content separately.
clear
local p “v1 v2 v3 v4”
local i=1
foreach var in `p’ {
if “`i'”==”1” {
local ttp “`””`var'””‘”
local ttpcomma “”`””`var'””‘””
}
else if “`i'”~=”1” {
local ttp “`ttp'””`” “`var'” “‘”
local ttpcomma `”`ttpcomma’,”`””`var'””‘” “‘}
local i=`i’+1
}display “`p'”
display `ttp’
display “`ttpcomma'”
At SSCC are some Stata programming essentials.
via Nick Cox
1. You want to look for ” as a literal character, not a delimiter.
2. Therefore compound double quotes `” “‘ must be used as delimiters.
replace tags = subinstr(tags, `”””‘, “”, .)
The awkward argument is
`” left compound double quote
” double quote to be taken literally
“‘ right compound double quote
A trick to avoid all this is to note that ” is char(34) [see
-asciiplot- from SSC for a cheat sheet] so that
replace tags = subinstr(tags, char(34), “”, .)
via Econometrics by Simulation: Remove a subset from a global – Stata.
local xyz a b c d e f g a b c d e
local a a b c
local b: subinstr local xyz “`a'” “”, all word
local c : list retokenize b // not necessary but removes excess spaces
disp “`c'”
From Jeremy Nighohossian is a useful cheat sheet for macros:
I have split the commands into two types – cmd and oper. cmd is a command on a single macro while oper requires two macros.
local/global macname : list cmd macname
cmd description Example
uniq Extracts the unique elements of the macro uniq “A B C B” returns “A B C”
dups Extracts the repeated elements of the macro dups “A B C B” returns “B”
sort Alphabetizes the elements of the macro sort “A B C B” returns “A B B C”
retokenize
sizeof Returns the number of elementslocal/global macname : list macro1 oper macro2
oper description Example
| Returns the union of both macros “A B C” | “A C D” returns “A B C D”
& returns the intersection of both macros “A B C” & “A C D” returns “A C”
– returns elements of macro1 less the elements that are present in macro2 “A B C” – “A C D” returns “B”
== tests whether macro1 is identical to macro2 regardless of order “A B C” == “A C B” returns 1
=== tests whether macro1 is identical to macro2 including order “A B C” == “A C B” returns 0
in tests whether all elements of macro1 are present in macro2 “A B C” in “A C D E B” returns 1