r - 通过在 R 中随时间增加计数来子集
问题描述
我有一个数据框,其中包含卖方、年份和月份的销售计数,称为sales_by_month
:
library(tidyverse)
sales_by_month <- tribble(
~Seller, ~Year, ~Month, ~Sales,
"John Doe", 2018, 1, 82,
"John Doe", 2018, 2, 72,
"John Doe", 2018, 3, 42,
"Sally Jane", 2018, 1, 25,
"Sally Jane", 2018, 2, 77)
我只需要那些销售额随时间增长的卖家对这个数据集进行子集化,我不知道该怎么做。
生成的子集数据集应包含;
Seller Year Month Sales
Sally Jane 2018 1 25
Sally Jane 2018 2 77
因为 Sally 的销售额在增加,而 John 的销售额在减少。
任何帮助将不胜感激!
解决方案
如何做到这一点实际上取决于您要如何定义随时间增加。定义随时间增加的一种方法是是否存在逐月增加。我的解决方案只是查看上个月是否有所增加,但这可以更改为以不同的方式看待它:
我们每个月都会计算变化。我们仅筛选上个月的内容,如果这是一个积极的变化。然后我们提取出唯一的卖家名称。
我们过滤我们在第 1 部分中获得的卖家名称。
下面的代码以及我们可以直接加载到 R 中的数据帧
library(tidyverse)
sales_by_month <- tribble(
~Seller, ~Year, ~Month, ~Sales,
"John Doe", 2018, 1, 82,
"John Doe", 2018, 2, 72,
"John Doe", 2018, 3, 42,
"Sally Jane", 2018, 1, 25,
"Sally Jane", 2018, 2, 77)
increased_from_last_month <- sales_by_month %>%
group_by(Seller) %>%
arrange(Seller, Year, Month) %>%
mutate(change = Sales - lag(Sales, default = 0)) %>%
summarise_all(last) %>%
filter(change > 0) %>%
pull(Seller) %>%
unique()
sales_by_month %>%
filter(Seller %in% increased_from_last_month)
推荐阅读
- azure - Azure VM 可用区和负载平衡
- java - 获取双卡电话通话记录(通话记录来自什么 SIM 卡)
- video - ffmpeg - 在我应用多遍工作流程时保持视频质量,每个工作流程都包括再次解码和编码,在视频编辑中
- c# - 用数组中的字符串填充数据集记录
- javascript - localStorage 属性不存储元素的超文本引用属性
- flutter - 一些可以帮助我在颤振中实现日历小部件
- swift - Swift:音频播放完毕后如何设置代码执行?
- ios - MultipeerConnectivity 在 iOS 14 上无法按预期工作
- c# - CrystalDecisions.CrystalReports.Engine.dll 中的 System.Runtime.InteropServices.COMException
- java - 如何在每个类 WebClient retryWhen 中避免硬编码