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 = Pat 列的数量)并将其附加在彼此下方。然后我想把Pat2放在Pat1下面,把Pat3放在Pat2下面,......

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

4

2 回答 2

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
.......
于 2012-11-06T22:17:10.607 回答
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
...
于 2012-11-06T13:51:59.523 回答