There are many issues with your code. Here's one way to do the inner loop.
/* one fake dataset */
set obs 5
gen var1 = 1
gen var2 = 2
gen var3 = "c"
gen z = 35
ds
/* keep part */
local masterlist "var1 var2"
local keeplist = ""
foreach i of local masterlist {
capture confirm variable `i'
if !_rc {
local keeplist "`keeplist' `i'"
}
}
keep `keeplist'
The key part is that you can't foreach i of varlist phantomvar
, since Stata will check the existence and error out. Similarly, putting the local name in special quotes will evaluate it, but you're trying to redefine. You may find set trace on
a useful feature in debugging.
This is somewhat better code:
unab allvars: _all
local masterlist "var1 var2 phantomvar"
local keeplist: list allvars & masterlist
keep `keeplist'