Reputation: 1309
Suppose I have a local macro containing some variable names
local indep "cat dog pig"
How do I drop pig
from the macro, if I want the macro to contain only cat
and dog
?
Upvotes: 4
Views: 5234
Reputation: 37208
The context is that you want to remove variable names from a string listing them. The subinstr()
solution in the OP's answer works only if the text to remove occurs just once as an entire variable name, and does not occur as part of another variable name. Thus the result of removing pig
from this list with equivalent but not identical syntax is
. local names "cat dog pig piglet"
. local names : subinstr local names "pig" "", all
. di "`names'"
cat dog let
That is not what you want. The solution is to insist that what is removed must be a word. In Stata, words are or could be separated by spaces (other than being bound by double quotes); in the case of Stata variable names, distinct variable names are always distinct words.
. local names "cat dog pig piglet"
. local names : subinstr local names "pig" "", word
. di "`names'"
cat dog piglet
When handling lists of variable names, Stata doesn't care about multiple spaces rather than single spaces, so neither need you. But if they offend, they can be reduced to single spaces.
See also the functions subinstr()
and subinword()
for approaches similar in spirit. In some older versions of Stata there were rather strict limits on string length for such functions, which made use of the construct used above : subinstr
advisable for all but very short lists.
Here, however, is a quite different solution:
. local names "cat dog pig piglet"
. local pig "pig"
. local names : list names - pig
. di "`names'"
cat dog piglet
In a program, that is often much better, especially if you want to remove several names (more generally "words") at once.
Upvotes: 6
Reputation: 1309
It seems I have found the answer myself..
local indep "cat dog pig"
local indep = subinstr("`indep'", "pig", "", .)
local indep = rtrim("`indep'")
but I am not sure if this is a good answer. This works only if pig
comes last in the macro.
Upvotes: 2