sxgn
sxgn

Reputation: 137

Generate a new macro prefixing words of an old macro

Define a macro try:

local try "a b c"

This will generate a macro with the value a b c.

Now I want a new macro try2 which takes the value da db dc. That is, I want to add the same prefix to each element of the old macro and define it as a new macro.

Upvotes: 2

Views: 81

Answers (2)

Felix Leung
Felix Leung

Reputation: 51

You could do this using Mata too.

local try "a b c"
mata: st_local("try2", invtokens("d" :+ tokens(st_local("try"))))

assert "`try2'" == "da db dc"

In words, this is what the second line does, explaining the innermost function first:

  1. st_local("try"): Access the contents in the local variable. This should evaluate to "a b c".
  2. tokens("a b c"): Split the string into tokens, e.g. tokens("a b c") -> ("a", "b", "c").
  3. "d" :+ ("a", "b", "c"): In Mata, you can concatenate strings with a +, and here :+ does this element-wise, so the result would be ("da", "db", dc").
  4. invtokens(("da", "db", dc")): Put the tokens back into a string, i.e. invtokens(("da", "db", dc")) -> "da db dc".
  5. st_local("try2", "da db dc"): The Mata equivalent of local try2 "da db dc".

You can find out more about the Mata functions st_local(), tokens(), and invtokens() with e.g. help mf_st_local.

Upvotes: 1

Nick Cox
Nick Cox

Reputation: 37278

There is, so far as I know, no function that specifically supports that in official Stata. For nearby functions, see help macrolists.

An old package listutil (SSC) includes various commands, prelist being pertinent. I wrote that, so it's not being negative about others' work that makes me recommend just applying general technique.

local try "a b c" 
local copy `try' 
gettoken first copy : copy 

while ("`first'" != "") { 
    local try2 `try2' d`first' 
    gettoken first copy : copy 
} 

di "try is {col 12} `try'"  
di "try2 is{col 12} `try2'" 

Upvotes: 2

Related Questions