Stata. How to "keep" a list of variables if some of them may not exist?

I have 100 .dta files. I need to β€œsave” some variables (I have a list of variables that I need to β€œsave”) and save temporary copies on the fly. Some variables may or may not exist in a particular .dta . I need Stata to save all variables that exist in .dta and ignore those that do not exist.

The following code has the wrong syntax, but it can serve as a good pseudo code to give a general idea of ​​what needs to 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?

+4
source share
1 answer

There are many problems in the code. Here is one way to make an 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 cannot foreach i of varlist phantomvar , as Stata will check for the presence and error. Similarly, a local name in special quotation marks will evaluate it, but you are trying to override it. You can find set trace on useful feature when debugging.

This is somewhat better code:

 unab allvars: _all local masterlist "var1 var2 phantomvar" local keeplist: list allvars & masterlist keep `keeplist' 
+7
source

Source: https://habr.com/ru/post/1485711/


All Articles