Reputation: 10112
I have some variables with dollar signs (i.e., $
) in the variable labels. This causes some problems downstream in my code (I later modify these labels and the dollar signs deregister as empty global macros). So I would like to replace these dollar signs with LaTeX's \textdollar
using Stata's subinstr()
function.
But I can't figure it out. Is this possible? Or should I resign to doing this more manually? Or by looking for other characters near or around the $
in the variable labels?
clear
set obs 10
generate x = runiform()
label variable x "Label with $mil"
generate y = runiform()
label variable y "Another label with $mil"
describe
foreach v of varlist * {
local name : variable label `v'
local name `=subinstr("`name'", "$mil", "\textdollar", .)'
label variable `v' "`name'"
}
describe
This removes the label altogether.
Upvotes: 2
Views: 1646
Reputation: 11102
(The problem has completely changed, which is why I give a separate answer.)
Having $something
in the variable label is somewhat problematic because Stata will treat it as a macro
and will therefore dereference it. What is actually Stata doing in your toy example? Let's see:
This is expected behavior:
. local name = subinstr("some text", " ", "xyz", .)
. display "`name'"
somexyztext
The following, which I don't know if documented, is not necessarily expected but crucial in understanding:
. local name = subinstr("some text", "", "xyz", .)
. display "`name'"
. (blank)
I put in the last line to emphasize that the local name
has nothing.
In your code Stata dereferences $mil
to nothing (because it's not declared beforehand; it's not meant to, of course). In fact,
label variable x "Label with $mil"
does not hold what you intend. Rather you want to delay macro substitution with \
:
label variable x "Label with \$mil"
For the other part, when you run this
local name `=subinstr("`name'", "$mil", "\textdollar", .)'
it evaluates to
local name `=subinstr("`name'", "", "\textdollar", .)'
and the local name
now holds nothing. That ends the story of why your code does what it does.
A solution might be:
clear
set obs 10
generate x = runiform()
label variable x "Label with \$mil"
generate y = runiform()
label variable y "Another \$mil"
describe
*-----
foreach v of varlist _all {
local name : variable label `v'
label variable `v' "`=subinstr("`name'\$mil", "\$mil", "\textdollar", .)'"
}
describe
but this only works if $mil
is at the end of the label text. If it is in the middle somewhere, another strategy must be used.
All this on Stata 12.1.
Upvotes: 2
Reputation: 11102
You are missing an argument in subinstr()
, what appears in help
as n
:
clear
set obs 10
generate x = runiform()
label variable x "Label with $"
local name: variable label x
local name = subinstr("`name'", "$", "\textdollar", .)
label variable x "`name'"
describe
Upvotes: 3