如何合并行,但将不同的值粘贴到 r 中的一列中?

How can I combine rows, but paste different values into one column in r?

我想合并具有几乎相同值的行,但我想合并不同的值,这样我就不会丢失以后要分析的信息。

我有以下数据集:

SessionId      Client id      Product_type       Item quantity
   1              1               Couch                1              
   1              1               Table                1
   2              2               Couch                1
   2              2               Chair                5

我想要这样的输出:

SessionId      Client id      Product_type       Item quantity
   1              1            Couch, Table           2
   2              2            Couch, Chair           6

所以我需要根据会话 ID 合并行。但是对于列产品类型,我想将字符名称粘贴在彼此后面,对于项目数量,我想对数量求和。我有更多的列,但这些值可以保持不变。

也许我需要分两步完成,但我不确定如何开始。希望有人能帮助我。

试试这个。

d %>% group_by(SessionId,Client_id) %>% 
  summarise(prod_type = toString(Product_type),
            sum_item_q = sum(Item_quantity, na.rm = T))

输出为:

# A tibble: 2 x 4
# Groups:   SessionId [2]
  SessionId Client_id prod_type    sum_item_q
      <int>     <int> <chr>             <int>
1         1         1 Couch, Table          2
2         2         2 Couch, Chair          6

数据

structure(list(SessionId = c(1L, 1L, 2L, 2L), Client_id = c(1L, 
                                                            1L, 2L, 2L), Product_type = c("Couch", "Table", "Couch", "Chair"
                                                            ), Item_quantity = c(1L, 1L, 1L, 5L)), row.names = c(NA, -4L), class = c("data.table", 
                                                                                                                                     "data.frame"))->d

可以这样实现

df <- read.table(text = "SessionId      'Client id'      Product_type       'Item quantity'
   1              1               Couch                1              
   1              1               Table                1
   2              2               Couch                1
   2              2               Chair                5", header = TRUE)

library(dplyr)

df %>% 
  group_by(SessionId, Client.id) %>% 
  summarise(Product_type = paste(Product_type, collapse = ", "),
            Item.quantity = sum(Item.quantity))
#> # A tibble: 2 x 4
#> # Groups:   SessionId [2]
#>   SessionId Client.id Product_type Item.quantity
#>       <int>     <int> <chr>                <int>
#> 1         1         1 Couch, Table             2
#> 2         2         2 Couch, Chair             6

reprex package (v0.3.0)

于 2020-05-23 创建

基础 R 解决方案:

aggregate(.~SessionId+Client_Id, within(df, {Product_type <- as.character(Product_type)}),
          FUN = function(x){if(is.integer(x)){sum(x)}else{toString(as.character(x))}})