简体   繁体   English

使用Stata检查变量的存在

[英]Checking variables' existence using Stata

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循环,但它不起作用:

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. 我还试图用of ,而不是in ......还是没有结果。 I get a message var2 not found and it stops executing. 我收到一条消息var2 not found并且它停止执行。 Does capture have to prefix the foreach ? capture必须以foreach为前缀吗? I tried that...did not work? 我试过......没用?

This is slightly subtle. 这有点微妙。

Given that var2 does not exist, Stata is still being instructed (within the else branch) to 鉴于var2不存在,Stata仍然被指示(在else分支内)

 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. - 第一次观察中的值 - 但由于var2不存在,Stata抱怨。

What you want is to display the name var2 , not its contents (which, once more, do not exist), and the fix is simply 你想要的是显示名称var2 ,而不是它的内容(再一次,不存在),修复只是

 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. 双引号分隔符的位置至关重要,以强制display不存在的事物的名称。 Names of things that do not exist are just arbitrary text, and Stata has no problem with such text. 不存在的事物的名称只是任意文本,Stata对此类文本没有任何问题。

In short, when fed to display 总之,当喂到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. 顺便说一下,你的循环只是覆盖了之前存储的结果集,但可能你会在适当的时候得到它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM