0

This might seem painfully easy, but say I create a Stata local macro called example:

local example "blah1 blah2 blah3"

I want to get just blah2 using the numerical index, in a way that might look like

example[2]

in another language. How does one do this in Stata?

Nick Cox
  • 35,529
  • 6
  • 31
  • 47

1 Answers1

2

If you run this script you will see four ways of getting the second word.

local example "blah1 blah2 blah3"

* 1 
tokenize "`example'"
di "`2'"

* 2 
local example2 : word 2 of `example'
di "`example2'"

* 3 
di "`: word 2 of `example''" 

* 4 
mata : words = tokens(st_local("example"))
mata : words[2]

In Stata (as opposed to Mata) the syntax words[2] is perfectly legal so long as words is a variable, meaning a column in the dataset, but a local macro in Stata is not a variable in that sense.

clear 
set obs 3 
gen words = "blah" + strofreal(_n) 
di words[2] 
Nick Cox
  • 35,529
  • 6
  • 31
  • 47