如何确认变量列表中所有相应变量的存在?

How do I confirm existence of all respective variables of a variable list?

类似的线程没有引导我解决以下问题。

我使用局部宏来指定一个具有多个变量的varlist,并想检查这个varlist中的每个变量是否存在于我使用的数据集中。以便快速了解数据集中不存在哪些变量。

到目前为止我已经尝试过以下代码:

local vlist caseid midx hidx v000-v013 v016 v021-v025 v101 v102

foreach v of local vlist {
   capture confirm variable `v'
    if !_rc {
        display in red "variable exists"
    }
    else {
        display in red "variable does not exist"
    }
}

代码运行完毕,但没有任何显示。我还尝试过故意在 varlist 中插入数据集中不存在的变量。没有任何变化。

有谁知道我该如何解决这个问题?

当我生成以下玩具变量时:

clear 
set obs 5

local vlist caseid midx hidx v000 v013 v014 v015 v016 v021 v025 v101 v102

foreach v of local vlist { 
    generate `v' = runiform()
}

这对我有用:

foreach v of local vlist { 
    capture confirm variable `v' 

    if !_rc { 
       display in red "variable `v' exists" 
    } 

    else { 
        display in red "variable `v' does not exist"
    } 
}

variable caseid exists
variable midx exists
variable hidx exists
variable v000 exists
variable v013 exists
variable v014 exists
variable v015 exists
variable v016 exists
variable v021 exists
variable v025 exists
variable v101 exists
variable v102 exists

如果我删除一个变量:

drop v000

(run the second loop again)

variable caseid exists
variable midx exists
variable hidx exists
variable v000 does not exist
variable v013 exists
variable v014 exists
variable v015 exists
variable v016 exists
variable v021 exists
variable v025 exists
variable v101 exists
variable v102 exists

如果您改为按如下方式定义本地宏 vlist

local vlist caseid midx hidx v000 v013-v016 v021 v025 v101 v102

(run the second loop again)

variable caseid exists
variable midx exists
variable hidx exists
variable v000 exists
variable v013-v016 does not exist
variable v021 exists
variable v025 exists
variable v101 exists
variable v102 exists

同理,如果添加两个不存在的变量var1var5

local vlist caseid midx hidx var1 v000 v013 v014 v015 v016 var5 v025 v101 v102

(run the second loop again)

variable caseid exists
variable midx exists
variable hidx exists
variable var1 does not exist
variable v000 exists
variable v013 exists
variable v014 exists
variable v015 exists
variable v016 exists
variable var5 does not exist
variable v025 exists
variable v101 exists
variable v102 exists

撇开你的显示问题不谈,你可以看看用户编写的命令checkfor2。它将为您提供三个 returns,其中包含一个列表,其中包含以下变量:a) 不存在,b) 存在,但有很多缺失,c) 存在,但缺失很少。