首页 > 解决方案 > 按订单 ID 汇总数据帧

问题描述

我正在使用一个数据集,该数据集显示作为客户订单一部分的产品的数量和价格。一个订单通常存在于多个产品中,因此存在多行。我想创建一个包含每个订单的总价格和产品数量的 df。我也想保留日期和客户ID。

orders <- orders %>% 
          group_by(orderid) %>% 
          summarise(date, customerid, sum(product qty), sum(price))

我最初是在考虑上面的脚本;但是它返回的行数与我以前的完全相同,而我希望它每个 orderid 只返回 1 行

有什么建议吗?

编辑:感谢您的帮助!这对获得我希望的结果有很大帮助:)

标签: rdplyr

解决方案


我创建了一些示例数据来向您展示如何继续

> dput(orders)
structure(list(order_id = c(1L, 1L, 1L, 2L, 2L, 3L), date = c("01-01-2020", 
"01-01-2020", "01-01-2020", "02-01-2020", "02-01-2020", "02-01-2020"
), customer_id = c("C1", "C1", "C1", "C2", "C2", "C3"), product_id = c("P1", 
"P2", "P3", "P4", "P5", "P1"), prod_qty = c(10L, 2L, 5L, 2L, 
3L, 5L), price = c(5L, 20L, 15L, 16L, 23L, 5L)), class = "data.frame", row.names = c(NA, 
-6L))

> orders
  order_id       date customer_id product_id prod_qty price
1        1 01-01-2020          C1         P1       10     5
2        1 01-01-2020          C1         P2        2    20
3        1 01-01-2020          C1         P3        5    15
4        2 02-01-2020          C2         P4        2    16
5        2 02-01-2020          C2         P5        3    23
6        3 02-01-2020          C3         P1        5     5

现在像这样进行

orders %>% group_by(order_id, date, customer_id) %>%
  summarise(products_purchased = n_distinct(product_id),
            total_price = sum(prod_qty*price)) %>%
  ungroup()

# A tibble: 3 x 5
  order_id date       customer_id products_purchased total_price
     <int> <chr>      <chr>                    <int>       <int>
1        1 01-01-2020 C1                           3         165
2        2 02-01-2020 C2                           2         101
3        3 02-01-2020 C3                           1          25

我认为这将解决您的问题并怀疑为什么要在声明中包含date和。这将有尽可能多的行,因为你有不同的 order_idscustomer_idgroup_by


推荐阅读