【问题标题】:reshape data with dplyr package使用 dplyr 包重塑数据
【发布时间】:2015-09-01 18:21:57
【问题描述】:

嘿, 我有这个数据集,我想重塑数据。

> dvd
   ID          Item
1   1   Sixth Sense
2   1         LOTR1
3   1 Harry Potter1
4   1    Green Mile
5   1         LOTR2
6   2     Gladiator
7   2       Patriot
8   2    Braveheart
9   3         LOTR1
10  3         LOTR2
11  4     Gladiator
12  4       Patriot
13  4   Sixth Sense

我想把数据做成这种格式。

#     ID                                               V1
#  1:  1 Sixth Sense,LOTR1,Harry Potter1,Green Mile,LOTR2
#  2:  2                     Gladiator,Patriot,Braveheart
#  3:  3                                      LOTR1,LOTR2
#  4:  4                    Gladiator,Patriot,Sixth Sense

我知道我可以使用此代码对 data.table 执行此操作

library(data.table)
as.data.table(DF)[, list(list(Item)), by = ID]

但我真的很想使用 dplyr 包.. 这是可能的? 我整天都在想这个,我不能忘记这个问题,它让我很生气:)

非常感谢您的帮助

【问题讨论】:

    标签: r dplyr


    【解决方案1】:

    有了tidyr(install)的开发版,简直就是

    nest(DF, Item)
    

    应该是

    library(dplyr)
    DF %>% group_by(ID) %>%
      summarise(Item = list(Item))
    

    【讨论】:

      【解决方案2】:

      我的做法是这样的:

      DF %>%
        group_by(ID) %>%
        summarise(V1 = paste0(Item, collapse = ", "))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-04-24
        • 2013-08-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-11-25
        • 2018-05-07
        相关资源
        最近更新 更多