I have a set of 18 Stata data files (one per year) whose names are:
{aindresp.dta, bindresp.dta, ... , rindresp.dta}
I want to eliminate some variables from each dataset. For this, I want to use the fact that many variables across dataset have the same name, plus a prefix given by the dataset prefix (a, b, c, ... r). For example, the variable rach12
is called arach12
in dataset aindresp.dta
, etc. Thus, to clean each dataset, I run a loop like the following:
clear all
local list a b c d e f g h i j k l m n o p q r
foreach var of local list {
use `var'indresp.dta
drop `var'rach12 `var'jbchc1 `var'jbchc2 `var'jbchc3 `var'xpchcf var'xpchc
save `var'indresp.dta, replace
}
The actual loop is much larger. I am deleting around 200 variables.
The problem is that some variables change name over time, or disappear after a few years. Other variables are added. Therefore, the loop stops as soon as a variable is not found. This is because the drop
command in Stata stops. Yet, that command has no option to force it to continue.
How can I achieve my goal? I would not like to go manually over each dataset.