r - 按订单 ID 汇总数据帧
问题描述
我正在使用一个数据集,该数据集显示作为客户订单一部分的产品的数量和价格。一个订单通常存在于多个产品中,因此存在多行。我想创建一个包含每个订单的总价格和产品数量的 df。我也想保留日期和客户ID。
orders <- orders %>%
group_by(orderid) %>%
summarise(date, customerid, sum(product qty), sum(price))
我最初是在考虑上面的脚本;但是它返回的行数与我以前的完全相同,而我希望它每个 orderid 只返回 1 行
有什么建议吗?
编辑:感谢您的帮助!这对获得我希望的结果有很大帮助:)
解决方案
我创建了一些示例数据来向您展示如何继续
> 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_id
group_by
推荐阅读
- swift - 当连接airpods时,routeChangeNotification在音频切换到扬声器后检测到newDeviceAvailable
- java - 这个类的作用是什么?
- c - 我的 For-Loop 不工作,但没有引发错误消息 - 它可能是什么?
- c# - C# - 如何从我的 Java 应用程序接收文件名和文件
- javascript - JS matchMedia:你也可以用这个来匹配屏幕吗?
- python-3.x - 使用 python / scapy 生成 100% 自定义 layer2 有效负载
- javascript - Chart.js - 沿 x(时间)轴合并天数到月数?
- .net - 将 netstandard 包安装到 .NET Core
- python - 如何匹配 A 和 B 之间的所有内容但不跨越预定义单词的边界
- android - 推送通知 ios 等效于 android