面板数据整理技巧 | Stata

  • 面板数据整理
    • 巧用前一期或下一期的取值为当期负值
    • 注意[]一定要与by id: 连用
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

set obs 50
gen a = _n
gen year = 1991 if inrange(a,1,10)
replace year = 1993 if inrange(a,11,20)
replace year = 1995 if inrange(a,21,30)
replace year = 1997 if inrange(a,31,40)
replace year = 2000 if inrange(a,41,50)
gen c = uniform()
bys year:gen id = _n

drop a

xtset id year

*生成属性(来自下一轮)
by id: gen next = c[_n+1]

*生成属性(来自上一轮)
by id: gen back = c[_n-1]

*生成属性(来自第一轮)
by id: gen first = c[1]

  • 对相邻两期数据做差分,得到两期间的差分值
 1
 2
 3
 4
 5
 6
 7
 8
 9
10

sort id year
order id year

*未成立,原因未知
gen diff_1 = d.c

*成立
bys id : gen diff_2 = c-c[_n-1]


1
2
3
4
5
6
7
8

drop in 1
replace c = . in 3
replace c = . in 7
replace c = . in 10
drop in 9
replace c = . in 10
replace c = . in 17

1
2

by id: replace c = c[_n-1] if !mi(c[_n-1])