Similar threads have not led me to solve the following problem.
I use a local macro to specify a varlist
with multiple variables and want to check whether each of the variables in this varlist
exists in the dataset I use. So as to get a quick overview which variables do not exist in the dataset.
I have tried the following code so far:
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"
}
}
The code runs through but nothing is displayed. I've also tried intentionally inserting variables in the varlist
that do not exist in the dataset. Nothing changed.
Does anyone know how I can overcome this problem?
When i generate the following toy variables:
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()
}
This works for me:
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
If i drop a variable:
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
If instead you define your local macro vlist
as follows:
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
Similarly, if you add two variables var1
and var5
that do not exist:
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
Leaving your display problem aside, you could have a look at the user-written command checkfor2
. It will give you three returns, containing a list with variables that are a) non-existing, b) existing, but with many missing and c) existing and with few missings.