楼主: cuiyanliliubing
5731 13

[其他] stata 数据合并问题 [推广有奖]

11
zerana 发表于 2010-4-18 13:47:33
是不是得到下面的结果:

+-------------------+
code   year     X
-------------------
1. 1   2005    12
2. 1   2006     0
3. 1   2007     0
-------------------
4. 2   2005    14
5. 2   2006    15
6. 2   2007     0
-------------------
7. 3   2005    17
8. 3   2006    14
9. 3   2007    11
-------------------
10. 4   2005     0
11. 4   2006    13
12. 4   2007    15
-------------------
13. 5   2005     0
14. 5   2006    16
15. 5   2007   167
-------------------
16. 7   2005     0
17. 7   2006     0
18. 7   2007    21
-------------------
19. 8   2005     0
20. 8   2006     0
21. 8   2007    56
-------------------
22. 9   2005     0
23. 9   2006     0
24. 9   2007    44
-------------------
25. 10   2005     0
26. 10   2006     0
27. 10   2007    37
+-------------------+

做法是先把三年对应变量分开存为三个文件,然后按照code合并,得到按照code来identify的三个变量X2005,X2006,X2007。然后按照上面网友说的reshape。即可。

12
liufayue 发表于 2010-4-19 11:52:35
在表1 中把X200*中数据为零的项也写出来,可能在处理时会简单一些。

13
sungmoo 发表于 2010-4-24 17:46:36
*若只生成非平衡面板,是不是要以下结果:
reshape long code,i(code*) j(year)
sort code year
keep if code<.
g x=.
foreach i of num 2005 2006 2007{
replace x=x`i' if year==`i'
}
drop *2005 *2006 *2007

14
sungmoo 发表于 2010-4-24 18:32:39
*设原始数据如下:
clear
inp code2005 code2006 code2007 x2005 x2006 x2007
1  2 3 12 15 11
2 3 4 14 14 15
3 4 5 17 13 167
. 5 7 . 16 21
. . 8 . . 56
. . 9 . . 44
. . 10 . . 37
end

*若以0补齐生成平衡面板,试一下:
reshape long code,i(code*) j(year)
sort code year
keep if code<.
g x=.
foreach i of num 2005 2006 2007{
replace x=x`i' if year==`i'
}
drop *2005 *2006 *2007
by code: g n=_n
by code: egen m=count(year)
expand 3 if m==1
expand 2 if n==2&m==2
sort code year
by code: replace n=_n
replace x=0 if n>m
replace year=. if n>m
by code: egen s=sum(year)
replace year=6018-s if year==.&m==2
replace year=s+n-1 if year==.&m==1&s==2005
replace year=2005+(n-2)*2 if year==.&m==1&s==2006
replace year=s-n+1 if year==.&m==1&s==2007
sort code year
drop n m s

您需要登录后才可以回帖 登录 | 我要注册

本版微信群
加好友,备注jltj
拉您入交流群
GMT+8, 2025-12-30 02:37