stata小小白

010 Stata:纵向合并

2019-07-16  本文已影响2人  凡有言说

Stata的合并有两类:一类是纵向合并,另外一类是横向合并。本篇介绍纵向合并的几种方法。

append using filename [filename ...] [, options]

*示例1
sysuse auto, clear
keep if foreign == 0
save domestic, replace 

sysuse auto, clear
keep if foreign == 1
save foreign, replace

use domestic, clear
append using foreign
*示例2:合并资产负债表

*(1)读入Excel文件并保存为dta文件

clear
cd C:\Users\Van\Desktop\download\append\数据的纵向合并

fs *.xls
local i = 1
foreach file in `r(files)' {
    import excel using `file', first case(lower) clear
    drop in 1/2
    save `i'.dta, replace
    local i = `i' + 1
}

*(2)纵向合并5个dta文件

*方法1
clear
append using 1.dta
append using 2.dta
append using 3.dta
append using 4.dta
append using 5.dta
count

*方法2
clear
append using 1 2 3 4 5
count

*方法3
*fs命令 + append
clear
fs *.dta
foreach file in `r(files)' {
    append using `file'
}
count

*方法4
*宏扩展函数 + append
clear
local files : dir "." files "*.dta"
dis`files'

foreach file in `files' {
    append using `file'
}
count

save 资产负债表, replace

此外,还有一个外部命令openall可以用于合并数据,详见
202 Stata命令:openall

当样本量小时fs+appnd 或 openall均可,当样本量大时,推荐宏扩展函数+append

参考资料:
【爬虫俱乐部】精通Stata之数据整理

上一篇下一篇

猜你喜欢

热点阅读