我想通过人年组合(面板数据)来计算值之间发生变化的频率。这模仿了Stata的命令xttrans
。索引6和7之间的过渡不应该包括在内,因为它不是一个人内部的过渡。
df = data.frame(id=c(1,1,1,1,1,1,1,2,2,2,2,2,2,2),
year=seq(from=2003, to=2009, by=1),
health=c(3,1,2,2,5,1,1,1,2,3,2,1,1,2))
这里是基本的R解决方案:
with(df, do.call(`+`, tapply(health, id, function(x){
x <- factor(x, levels = min(health):max(health))
table(x[-length(x)], x[-1])
})))
# 1 2 3 4 5
# 1 2 3 0 0 0
# 2 1 1 1 0 1
# 3 1 1 0 0 0
# 4 0 0 0 0 0
# 5 1 0 0 0 0