拆分数据帧的列以合并重复变量

时间:2017-07-11 16:41:32

标签: r dataframe split

我通常会在此处发布的问题中找到答案,但我似乎无法找到这个问题,所以这是我的处女问题:

我有一个数据框,其中一列有重复值,我想拆分其他列,第一列只有1个值,而且比原始数据框中的列数多。

示例:

df <- data.frame(test = c(rep(1:5,3)), time = sample(1:100,15), score = sample(1:500,15))

原始数据框有3列15行。

它会变成一个包含5行的数据框,列将分为7列:&#39; test&#39;,&#39; time1&#39;,&#39; time2&#39;, &#39; time3&#39;,&#39;得分1&#39;,得分2&#39;,&#39;得分3&#39;。

有谁知道如何做到这一点?

2 个答案:

答案 0 :(得分:1)

我认为在data.table-package中使用dcastrowid非常适合此任务:

library(data.table)
dcast(setDT(df), test ~ rowid(test), value.var = c('time','score'), sep = '')

结果:

   test time1 time2 time3 score1 score2 score3
1:    1    52     3    29     21    131     45
2:    2    79    44     6    119      1    186
3:    3    67    95    39     18    459    121
4:    4    83    50    40    493    466    497
5:    5    46    14     4    465      9     24

答案 1 :(得分:0)

请试试这个:

df <- data.frame(test = c(rep(1:5,3)), time = sample(1:100,15), score = sample(1:500,15))

df$class <- c(rep('a', 5), rep('b', 5), rep('c', 5))


df <- split(x = df, f = df$class)

binded <- cbind(df[[1]], df[[2]], df[[3]])

binded <- binded[,-c(5,9)]


> binded
  test time score class time.1 score.1 class.1 time.2 score.2 class.2
1    1   40   404     a     57     409       b     70      32       c
2    2    5   119     a     32     336       b     93     177       c
3    3   20   345     a     44      91       b    100      42       c
4    4   47   468     a     60     265       b     24     478       c
5    5   16    52     a     38     219       b      3      92       c

让我知道它是否适合你!