【问题标题】:Subset by increasing count over time in R通过在 R 中随时间增加计数来子集
【发布时间】:2019-01-08 18:22:01
【问题描述】:

我有一个数据框,其中包含按卖家、年份和月份划分的销售计数,称为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 的销售额在减少。

任何帮助将不胜感激!

【问题讨论】:

  • 您好,将数据包含在我们可以轻松放入环境中使用的表单中会很有帮助。你可以看看stackoverflow.com/questions/5963269/…,看看如何制作一个可重现的好例子!
  • 如果 John Doe 在 3 月达到 75 岁怎么办?
  • @sahir 感谢您的链接,我将努力添加一个可重现的示例!
  • 我们可以假设数据是排序的吗?如果是这样,您可以使用df[as.logical(ave(df$Sales, df$Seller, FUN = function(x) !any(x - shift(x) &lt; 0, na.rm = TRUE))), ]
  • 你想如何确定增加?如果最早一个月的销售额大于最近一个月的销售额?如果他们掉在中间但又捡起来怎么办?

标签: r


【解决方案1】:

首先,在Sales(我将其命名为dif)中创建一个表示差异的变量。如果dif &lt; 0,则表示某人的销售额存在递减价值。

library(dplyr)

df %>% arrange(Seller, Year, Month) %>%
  group_by(Seller) %>%
  mutate(dif = c(0, diff(Sales))) %>%
  filter(all(dif >= 0)) %>%
  select(-dif) # drop dif

#   Seller     Year Month Sales
#   <fct>     <int> <int> <int>
# 1 SallyJane  2018     1    25
# 2 SallyJane  2018     2    77

更简洁:

df %>% group_by(Seller) %>%
  arrange(Seller, Year, Month) %>%
  filter(all(c(0, diff(Sales)) >= 0))

【讨论】:

    【解决方案2】:

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

    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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-05
      • 1970-01-01
      • 2014-07-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-12
      • 1970-01-01
      相关资源
      最近更新 更多