I have 30+ .dta files that I would like to combine into dataset. They are all saved in the same folder. What is the fastest way to achieve this?
-
Login or Register
- Log in with
clear*
local filenames: dir "." files "*.dta"
tempfile building
save, emptyok
foreach f of local filenames {
use `"`f'"', clear
/* INSERT HERE EITHER
append using `building'
OR
merge 1:1 or perhaps 1:m key_variables using `building'
*/
save `"`building'"', replace
}
use `building', clear
save combined_data_set, replace
clear
* get a list of datasets in the current directory
local flist : dir . files "*.dta"
dis `"`flist'"'
* loop over each dataset and append to the data in memory;
* it's OK to append if we start with no data;
* create a numeric source variable and build labels as we go
gen source = .
local i 0
foreach f in `flist' {
append using "`f'"
replace source = `++i' if mi(source)
label def source `i' "`f'", add
}
* attach the value labels to the source variable
label value source source
tab source
Comment