2012-11-06 71 views
1

比方说,我有以下的数据帧:重复和重新排列在数据帧列

> df = data.frame(seq(0, 150, length.out=11), 1:11, rep(0, 11), sample(1:50, 11), 
+ sample(1:50, 11), sample(1:50, 11)) 
> colnames(df) = c("Time", "Inc", "Side", "Pat1", "Pat2", "Pat3") 
> df 
    Time Inc Side Pat1 Pat2 Pat3 
1  0 1 0 48 49 13 
2 15 2 0 43 33 15 
3 30 3 0 27 48 38 
4 45 4 0 41 47 46 
5 60 5 0 11 25 37 
6 75 6 0 5 15 4 
7 90 7 0 17 22 2 
8 105 8 0 10 41 24 
9 120 9 0 45 21 33 
10 135 10 0 19 26 41 
11 150 11 0 25 42 45 

现在我想重复第3列N次(N =帕特列数)和其附加一个在彼此之下。然后,我想将Pat2放置在Pat1下面,Pat3放在Pat2下面,...

我的第一个意思是将df分割成Time/Inc/Side部分和Pat部分,但我在安排每个下面的列时遇到问题其他。有什么建议么?

回答

2

使用reshape2melt

# recreate the data 
df = data.frame(seq(0, 150, length.out=11), 1:11, rep(0, 11), sample(1:50, 11), 
sample(1:50, 11), sample(1:50, 11)) 
colnames(df) = c("Time", "Inc", "Side", "Pat1", "Pat2", "Pat3") 
library(reshape2) 

melt(df, id.vars = c('Time', 'Inc', 'Side')) 

    Time Inc Side variable value 
1  0 1 0  Pat1  7 
2 15 2 0  Pat1 18 
3 30 3 0  Pat1 10 
4 45 4 0  Pat1 35 
5 60 5 0  Pat1 30 
6 75 6 0  Pat1 32 
7 90 7 0  Pat1 12 
8 105 8 0  Pat1 38 
9 120 9 0  Pat1 26 
....... 
+0

这是更简单的替代方法。没有意识到软件包reshape2。谢谢! – Markus

1
reshape(df,direction="long",varying=list(4:6), 
    idvar=names(df)[1:3],times=names(df)[4:6],v.names="value") 
       Time Inc Side time value 
0.1.0.Pat1  0 1 0 Pat1 47 
15.2.0.Pat1  15 2 0 Pat1 16 
30.3.0.Pat1  30 3 0 Pat1 19 
45.4.0.Pat1  45 4 0 Pat1 46 
60.5.0.Pat1  60 5 0 Pat1 21 
75.6.0.Pat1  75 6 0 Pat1 44 
90.7.0.Pat1  90 7 0 Pat1 18 
105.8.0.Pat1 105 8 0 Pat1 11 
120.9.0.Pat1 120 9 0 Pat1 38 
...