【问题标题】:Splitting columns of a dataframe to merge a repetitive variable拆分数据框的列以合并重复变量
【发布时间】:2017-07-11 16:41:31
【问题描述】:

我通常在以前发布的问题中找到答案,但我似乎找不到这个,所以这是我的第一个问题:

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

例子:

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

原始数据框有 3 列 15 行。

它会变成一个有 5 行的数据框,列将分为 7 列:'test'、'time1'、'time2'、'time3'、'score1'、score2'、'score3'。

有人知道如何做到这一点吗?

【问题讨论】:

  • 欢迎来到 Stack Overflow!请拿起tour,环顾四周,并通读help center,尤其是How do I ask a good question?。请添加您迄今为止为解决问题所做的工作,以及您在解决问题时遇到的困难的描述
  • 我尽力了,但我不知道如何将(所需的)输出复制/粘贴到问题中。感谢您的欢迎,我阅读了帮助中心,如果我的问题低于标准,我很抱歉。我会再读一遍。

标签: r dataframe split


【解决方案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

【讨论】:

    【解决方案2】:

    请试试这个:

    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
    

    让我知道它是否适合你!

    【讨论】:

    • 你可以把这个binded &lt;- cbind(df[[1]], df[[2]], df[[3]])改成binded =do.call(cbind,df)
    • 没错!谢谢你的提示!我认为我必须更频繁地使用do.call
    • 巧妙的解决方案,感谢您这么快回复。但我认为 h3rm4n 的解决方案对于这个特定问题来说更干净一些。
    猜你喜欢
    • 1970-01-01
    • 2016-04-04
    • 1970-01-01
    • 1970-01-01
    • 2021-01-19
    • 1970-01-01
    • 1970-01-01
    • 2019-09-17
    • 2020-05-05
    相关资源
    最近更新 更多