I have 100 dta
files. I have a list of variables that I need to keep
and save temporary copies on the fly. Some variables may or may not exist in a certain dta
.
I need Stata to keep all variables that exist in a dta
and ignore those that do not exist.
The following code has wrong syntax, but it could serve as a good pseudo code to give one a general idea of what should be done:
forval j = 1/100 {
use data`j'
local myVarList =""
foreach i of varlist var1 var2 var3 var4 var5 var6 var7 var8 {
capture sum `i'
if _rc = 0 {
`myVarList' = `myVarList'" "`i'
}
}
keep `myVarList'
save temporaryData`j'
}
Is there any way to do this?
There are many issues with your code. Here's one way to do the inner loop.
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 findset trace on
a useful feature in debugging.This is somewhat better code: