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

时间:2018-05-09 12:05:25

标签: variables stata capture stata-macros

类似的线程并没有让我解决以下问题。

我使用本地宏来指定具有多个变量的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中插入数据集中不存在的变量。什么都没有改变。

有谁知道如何克服这个问题?

2 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:0)

将显示问题放在一边,您可以查看用户编写的命令checkfor2。它将为您提供三个返回,其中包含一个列表,其中包含以下变量:a)不存在,b)存在,但有许多缺失,c)存在并且缺少很少。

相关问题