2011-03-13 72 views
8

這是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,使得一個簡單的解決方案?

回答

12

reshape能猜出它的許多論點。在這種情況下,指定以下內容即可。沒有包被使用。

reshape(d1, dir = "long", varying = 3:6, sep = "_") 

,並提供:

 subject  x0 time x1 x2 id 
1.2000  id1 male 2000 1 1 1 
2.2000  id2 female 2000 2 2 2 
1.2005  id1 male 2005 5 5 1 
2.2005  id2 female 2005 6 6 2 
+0

不錯!但是當變量被命名爲_sample_1_2000_等等時會發生什麼......使用'sep ='選項可以更復雜嗎? – Fred 2011-03-14 14:05:34

+2

@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

4

這裏是使用reshape2包一個簡單的例子:

library(reshape2) 
library(stringr) 

# it is always useful to start with melt 
d2 <- melt(d1, id=c("subject", "x0")) 

# redefine the time and x1, x2, ... separately 
d2 <- transform(d2, time = str_replace(variable, "^.*_", ""), 
        variable = str_replace(variable, "_.*$", "")) 

# finally, cast as you want 
d3 <- dcast(d2, subject+x0+time~variable) 

現在你不需要甚至指定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, 
+ x3_2000 = 1:2, 
+ x3_2005 = 5:6, 
+ x4_2000 = 1:2, 
+ x4_2005 = 5:6 
+) 
> 
> d2 <- melt(d1, id=c("subject", "x0")) 
> d2 <- transform(d2, time = str_replace(variable, "^.*_", ""), 
+      variable = str_replace(variable, "_.*$", "")) 
> 
> d3 <- dcast(d2, subject+x0+time~variable) 
> 
> d3 
    subject  x0 time x1 x2 x3 x4 
1  id1 male 2000 1 1 1 1 
2  id1 male 2005 5 5 5 5 
3  id2 female 2000 2 2 2 2 
4  id2 female 2005 6 6 6 6 
+0

謝謝,這是非常有用的。不太清楚'變換'在做什麼(幫助文件不是很有用),也不知道如何解釋'「^。* _」'和'「_。* $」'。我問,因爲有些變量實際上被命名爲「sample_1_2000」等等...... – Fred 2011-03-13 03:34:47

+0

也許這對於名爲「sample_1_2000」的年份數據等更直觀:'temp1 < - transform(temp,time = str_sub(variable,-4),變量= str_sub(變量,1,str_length(變量)-5))' – Fred 2011-03-13 03:52:02

+0

@Fred它取決於變量名稱的格式。如果字符(至少有一部分)的長度是固定的,那麼你的方法就容易了。否則,正則表達式更加靈活。 – kohske 2011-03-13 05:05:03

相關問題