Information about Stata macros: number of elements and order within locals and globals

Especially when running loops (see our posts here), it can be important to get more information about a macro, such as the length, or its first or last element.

Return the number of elements of a macro

how many elements are stored in a macro (local or gobal). For calculating / displaying the length of a macro, simply write:

// For global ${myglobal}
global myglobal="Arkansa Nebraska"
local num : word count ${myglobal}

// For local `mylocal'
local mylocal="Arkansa Nebraska"
local num : word count `mylocal'

di "`num'" // displays the number of elements in the respective macro

Return the first element of a macro

For returning the first element of a macro in Stata, simply write:

tokenize ${myglobal}
local firstword="`: word 1 of ${myglobal}'"
di "`firstword'"

And replace ${myglobal} accordingly if you want to return the first word of a local instead.

Leave a Reply