I have a number of variables whose name begins with the prefix indoor
. What comes after indoor
is not numeric (that would make everything simpler).
I would like a tabulation for each of these variables.
My code is the following:
local indoor indoor*
foreach i of local indoor {
tab `i' group, col freq exact chi2
}
The problem is that indoor
in the foreach
command resolves to indoor*
and not to the list of the indoor
questions, as I hoped. For this reason, the tab
command is followed by too many variables (it can only handle two) and this results in an error.
The simple fix is to substitute the first command with:
local indoor <full list of indoor questions>
But this is what I would like to avoid, that is to have to find all the names for these variables and then paste them in the code. It seems there is a quicker fix for this but I can't think of any.
You could do this with
This question has two parts:
1. How to assign multiple variable names to a local macro
As others have noted, the obvious choice here is the use of the commands
ds
andunab
:2. How to automate the tabulation of variables sharing a common prefix
For this part, the simplest and most 'valid' loop syntax in the context of Stata is in fact the one proposed by @Vadim (and which was down-voted):
Undoubtedly, one could mix the two approaches but in this case it is just needless and inefficient.
The trick is to use
ds
orunab
to create the varlist expansion before asking Stata to loop over values in theforeach
loop.Here's an example of each:
**USE
ds
TO CREATE YOUR VARLIST FOR THEforeach
LOOP:**LET'S CLEAN UP YOUR TABLES A BIT WITH SOME HEADERS VIA
display
**YOUR
tab
TABLESOR using
unab
instead:The advantages of
ds
come into play if you want to select your indoor vars using a tricky selection rule, like selecting indoor vars based on information in the variable label or some other characteristic.This would work. It is almost identical to the code in the question.