這是Stata在一步處理的數據分析中的一個基本問題。使用多個變量和一些不變的時間將數據框重新整形爲面板
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
)
S.T.:
了2000年和2005年(X1,X2)創建時間不變的數據(X0)和隨時間變化的數據範圍內的數據幀
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
S.T.做到這一點
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,使得一個簡單的解決方案?
不錯!但是當變量被命名爲_sample_1_2000_等等時會發生什麼......使用'sep ='選項可以更復雜嗎? – Fred 2011-03-14 14:05:34
@Fred,使用'split'參數代替'sep',即'reshape(d1,dir =「long」,varying = 3:6,split = list(regexp =「_2」,include = TRUE)) ''或者將這種情況減少到問題中的一種情況,即'重塑(setNames(d1,sub(「sample_」,「」,names(d1))),dir =「long」,vary = 3:6,sep = 「_」)' – 2011-03-14 16:35:26