重复并重新排序数据框中的列

时间:2012-11-06 13:22:05

标签: r dataframe

假设我有以下数据框:

> 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 = Pat列的数量)并将它们相互重叠。然后我想把Pat2放在Pat1下面,Pat2下面的Pat3,......

我的第一个意图是将df拆分为Time / Inc / Side部分和Pat部分,但是我将列安排在彼此之下时遇到了问题。有什么建议?

2 个答案:

答案 0 :(得分: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
.......

答案 1 :(得分: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
...