I want to loop through different files:
forvalues y=2014/2022 {
use var1 var2 var3 using "file_`y'.dta"
save "file2_`y'
}
However, some of the files have var names VAR1 VAR2 var3
instead of var1 var2 var3
.
How do I make the statement case insensitive?
I'm not sure there's a concise way to do this, but here's an example using describe
and capture
to first check if the variable is contained in the .dta file.
First make the simple data examples with different cases:
tempfile the_data1 the_data2
clear
input var1 VAR2 var3
0 1 0
end
save `the_data1', replace
clear
input var1 var2 VAR3 // note uppercase is different from above
0 1 0
end
save `the_data2', replace
Then this loop handles the different names. The outer loop goes through the two files and creates an empty local myvarlist
which will contain the appropriate variable names for that file. The capture
line tries a describe command of the lowercase variable. If it works (_rc==0
), the lowercase name is added to the list. If it fails (rc!=0
), the uppercase name is added to the list. After looping through the variables, the use
line works because the cases have all been corrected.
forvalues i=1/2 {
local myvarlist ""
foreach myvar in var1 var2 var3 {
capture noisily describe `myvar' using `the_data`i''
if (_rc==0) local myvarlist "`myvarlist' `myvar'"
if (_rc!=0) local myvarlist = "`myvarlist' " + upper("`myvar'")
}
use `myvarlist' using `the_data`i''
describe
* Save file here
}