首页 > 解决方案 > 通过在 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 的销售额在减少。

任何帮助将不胜感激!

标签: r

解决方案


如何做到这一点实际上取决于您要如何定义随时间增加。定义随时间增加的一种方法是是否存在逐月增加。我的解决方案只是查看上个月是否有所增加,但这可以更改为以不同的方式看待它:

  1. 我们每个月都会计算变化。我们仅筛选上个月的内容,如果这是一个积极的变化。然后我们提取出唯一的卖家名称。

  2. 我们过滤我们在第 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)

推荐阅读