Reputation: 1713
I have already asked a question how to check for a variable's existence. Nick Cox answered it. Then I tried to modify the answer and to use a foreach
loop, but it did not work:
foreach var in var1 var2 var3 {
capture su `var', meanonly
if _rc == 0 {
local varMean = r(mean)
local varMin = r(min)
local varMax = r(max)
}
else display `var' "DOES NOT EXIST"
}
I also tried to use of
instead of in
...still no result. I get a message var2 not found
and it stops executing. Does capture
have to prefix the foreach
? I tried that...did not work?
Upvotes: 2
Views: 2156
Reputation: 37183
This is slightly subtle.
Given that var2
does not exist, Stata is still being instructed (within the else
branch) to
display `var' "DOES NOT EXIST"
which is to be interpreted as
display var2 "DOES NOT EXIST"
So, it first sees
display var2
which it is predisposed to interpret as
display var2[1]
-- the value in the first observation -- but as said var2
does not exist, and Stata complains.
What you want is to display the name var2
, not its contents (which, once more, do not exist), and the fix is simply
else display "`var' DOES NOT EXIST"
The position of the double quote delimiter is crucial, to enforce display
of the name of the thing that does not exist. Names of things that do not exist are just arbitrary text, and Stata has no problem with such text.
In short, when fed to display
"`macro'"
is a string to be displayed, but
`macro'
is the name of a variable or scalar to be displayed, or otherwise a macro with defined content to be displayed.
By the way, your loop just overwrites the previous set of stored results, but presumably you will get to that in due course.
Upvotes: 8