Stata Random Tips

Tip # 1 : Extract all text from a macro after a specific letter

Say that we have the following macro

local sp stata.professor

we want to extract anything that comes after the period (.), we can use the following code:

loc var =substr("`sp'",strpos("`sp'",".")+1,.)
display "`var'"


Tip #2: Extract specific text from a macro

Let’s say we have the following macro

loc p one two three(check) ttype(compact)

We aim to extract ttype(compact) from the above macro. We can use the function substr to do that. substr picks text based on the position of the given text. So counting all the letters and spaces in the above macro, ttype(compact)  starts from letter count of 22 and has 14 characters in it, therefore, the substr function will look like:

display substr("`p'",22,14)


Tip #3: Find string position in a macro or variable

An immediate question that comes to mind in Tip#2 above is that how do we get the value of 22, i.e., the position of the string in a macro. We can use the strpos function to do that, so:

display strpos("`p'","ttype(")


Tip #4: Count number of characters in a macro

we can use the length function for this purpose. So let us make a macro with the line “This is my line”

local line "This is my line"
display length("`line'")

Note that the white spaces are also counted as characters.


Tip #5: Two-stage macro expansion

We know that Stata macros can be used to hold values or string. For example,

local 1 make

To see the contents of this macro, we shall type:

display "`1'"

. make

A two-stage expansion will involve:

local i 1

macro i has a value 1. Since, 1 is itself a macro, we can reach the contents of 1 by:

display "``i''"

The first expansion will reveal 1 and the second expansion will reveal make.