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(")