首页 > 解决方案 > 如何计算发生之间的时间(和发生的持续时间)

问题描述

我正在处理以下挑战,非常感谢任何帮助。

考虑我有一个包含以下信息的数据表。

Store   Day           In stock ?  Out of stock ?
Store A 01 - 01 - 19  1           0
Store A 02 - 01 - 19  0           1
Store A 03 - 01 - 19  0           1
Store A 04 - 01 - 19  1           0
Store A 05 - 01 - 19  1           0
Store A 06 - 01 - 19  0           1
Store A 07 - 01 - 19  0           1
Store A       …       0           1
Store B 01 - 01 - 19  1           0
Store B 02 - 01 - 19  0           1
Store B       …       0           1

对于每家商店,我想计算连续缺货或缺货的天数。这两列是二元的,并且互斥。因此对于商店 A,结果将是:

Store     Duration in stock   Duration out of stock  
Store A   1
Store A                       2
Store A   2
Store A                       3

我需要为大型数据集(数百家商店的每小时值)执行此操作,因此希望将其自动化。此外,我想对“库存持续时间”和“缺货持续时间”做进一步的分析,例如平均值、极值、百分位数等。因此,数据需要以这样的方式组织,这将是可能的.

我还没有找到解决这个问题的方法。任何见解都会很好!

以下逗号分隔值:

Store;Day;In stock?;Out of stock?
Store A;01-01-19;1;0
Store A;02-01-19;0;1
Store A;03-01-19;0;1
Store A;04-01-19;1;0
Store A;05-01-19;1;0
Store A;06-01-19;0;1
Store A;07-01-19;0;1
Store A;…;0;1
Store B;01-01-19;1;0
Store B;02-01-19;0;1
Store B;…;0;1

标签: r

解决方案


这是一种使用dplyr. 首先,我使用 lubridate 将日期列转换为日期,假设它是日-月-年(因此是 dmy)顺序。

然后,对于每家商店,计算我们所处的“库存期”,每次在进货和缺货之间切换时都是新货。

使用它和商店,我将每列中的数字相加。

library(dplyr)
df %>%
  mutate(Day = lubridate::dmy(Day)) %>%
  group_by(Store) %>%
  mutate(stock_period = cumsum(In_stock != lag(In_stock, default = ""))) %>%
  group_by(Store, stock_period) %>%
  summarise(start = min(Day),
            end   = max(Day),
            In_stock = sum(In_stock), 
            Out_of_stock = sum(Out_of_stock))

# A tibble: 6 x 6
# Groups:   Store [2]
  Store   stock_period start      end        In_stock Out_of_stock
  <chr>          <int> <date>     <date>        <int>        <int>
1 Store A            1 2019-01-01 2019-01-01        1            0
2 Store A            2 2019-01-02 2019-01-03        0            2
3 Store A            3 2019-01-04 2019-01-05        2            0
4 Store A            4 2019-01-06 2019-01-07        0            2
5 Store B            1 2019-01-01 2019-01-01        1            0
6 Store B            2 2019-01-02 2019-01-02        0            1

使用此源数据:

df <- read.table(header = T, stringsAsFactors = F,
  text = "Store Day In_stock Out_of_stock
'Store A' 01-01-19 1 0
'Store A' 02-01-19 0 1
'Store A' 03-01-19 0 1
'Store A' 04-01-19 1 0
'Store A' 05-01-19 1 0
'Store A' 06-01-19 0 1
'Store A' 07-01-19 0 1
'Store B' 01-01-19 1 0
'Store B' 02-01-19 0 1") 

推荐阅读