Download Learning Stata

Transcript
8.2. COMPOUND DOUBLE QUOTES
71
1. Define a macro called groceries with pears, apples, strawberries,
yogurt, wine and cheese in it and put it in alphabetical order.
2. Define a macro called union which contains the members of the
macro `animals' and `groceries' and then use a macro extended list function to display the number of words it contains.
3. Sort `union' and display the position of the word “wine” using a
macro extended list function.
levelsof
function
The levelsof command lists distinct values of a variable. Adding the option
local stores them in a macro. The syntax is:
levelsof variable, local(macroname)
levelsof is frequently used to loop through subpopulations within a dataset.
In particular, Stata’s svy doesn’t permit the prefix by, but combining levelsof with a foreach loop lets us run a survey-weighted regression separately
for each race, thus recreating by’s functionality. The following example, taken
from UW-Madison SSCC (2014) illustrates.
levelsof race, local(races)
foreach race of local races {
display _newline(2) "Race=`race'"
svy, subpop(if race==race'): reg income age i.education
}
8.2
Compound double quotes
Sometimes macros themselves contain double quotes. For example, imagine
we defined a macro of potential answers to a survey question and then tried to
display its contents in Stata’s viewer.
local answers yes no "do not know"
display "`answers'"
Why the error? To understand it, consider the macro from Stata’s perspective.
Stata reads our command and before it does anything else substitutes `answers' with its literal value, yes no "do no know". That means it really sees
display "yes no "do not know""