这是Stata一步处理的数据分析中的一个基本问题。
创建一个宽数据框,其中包含时不变数据 (x0) 和 2000 年和 2005 年的时变数据 (x1,x2):
d1 <- data.frame(subject = c("id1", "id2"),
x0 = c("male", "female"),
x1_2000 = 1:2,
x1_2005 = 5:6,
x2_2000 = 1:2,
x2_2005 = 5:6
)
英石
subject x0 x1_2000 x1_2005 x2_2000 x2_2005
1 id1 male 1 5 1 5
2 id2 female 2 6 2 6
我想把它塑造成一个面板,所以数据看起来像这样:
subject x0 time x1 x2
1 id1 male 2000 1 1
2 id2 female 2000 2 2
3 id1 male 2005 5 5
4 id2 female 2005 6 6
我可以用reshape
st做到这一点
d2 <-reshape(d1,
idvar="subject",
varying=list(c("x1_2000","x1_2005"),
c("x2_2000","x2_2005")),
v.names=c("x1","x2"),
times = c(2000,2005),
direction = "long",
sep= "_")
我主要担心的是,当你有几十个变量时,上面的命令会变得很长。一种是简单地输入stata
:
reshape long x1 x2, i(subject) j(year)
R中有这么简单的解决方案吗?