应用滚动功能时如何显示缺失日期

问题描述

假设我有一些保险单的数据df

library(tidyverse)
library(lubridate)

#Example data
d <- as.Date("2020-01-01",format = "%Y-%m-%d")
set.seed(50)
df <- data.frame(id = 1:10,activation_dt = round(runif(10)*100,0) +d,expiry_dt = d+round(runif(10)*100,0)+c(rep(180,5),rep(240,5)))

> df
   id activation_dt  expiry_dt
1   1    2020-03-12 2020-08-07
2   2    2020-02-14 2020-07-26
3   3    2020-01-21 2020-09-01
4   4    2020-03-18 2020-07-07
5   5    2020-02-21 2020-07-27
6   6    2020-01-05 2020-11-04
7   7    2020-03-11 2020-11-20
8   8    2020-03-06 2020-10-03
9   9    2020-01-05 2020-09-04
10 10    2020-01-12 2020-09-14

我想查看每个月有多少个策略处于活动状态。我是通过以下方法完成的。

# Getting required result

df %>% arrange(activation_dt) %>% 
  pivot_longer(cols = c(activation_dt,expiry_dt),names_to = "event",values_to = "event_date") %>%
  mutate(dummy = ifelse(event == "activation_dt",1,-1)) %>%
  mutate(dummy2 = floor_date(event_date,"month")) %>%
  arrange(dummy2) %>% group_by(dummy2) %>%
  summarise(dummy=sum(dummy)) %>%
  mutate(dummy = cumsum(dummy)) %>%
  select(dummy2,dummy)

# A tibble: 8 x 2
  dummy2     dummy
  <date>     <dbl>
1 2020-01-01     4
2 2020-02-01     6
3 2020-03-01    10
4 2020-07-01     7
5 2020-08-01     6
6 2020-09-01     3
7 2020-10-01     2
8 2020-11-01     0

现在我在处理丢失的月份方面遇到问题,例如2020年4月至2020年6月等。

解决方法

一个data.table解决方案:

  1. 生成月份序列
  2. 使用非等额联接来查找每月有效的策略并对其进行计数
library(lubridate)
library(data.table)

setDT(df)
months <- seq(lubridate::floor_date(mindat,'month'),lubridate::floor_date(max(df$expiry_dt),by='month')
months <- data.table(months)

df[,c("activation_dt_month","expiry_dt_month"):=.(lubridate::floor_date(activation_dt,lubridate::floor_date(expiry_dt,'month'))]

df[months,.(months),on = .(activation_dt_month<=months,expiry_dt_month>=months)][,.(nb=.N),by=months]

       months nb
 1: 2020-01-01  4
 2: 2020-02-01  6
 3: 2020-03-01 10
 4: 2020-04-01 10
 5: 2020-05-01 10
 6: 2020-06-01 10
 7: 2020-07-01 10
 8: 2020-08-01  7
 9: 2020-09-01  6
10: 2020-10-01  3
11: 2020-11-01  2
,

如果您有兴趣,这里是另一种tidyverse / lubridate解决方案。 data.table版本会更快,但这可以为您带来正确的结果,而且间隔数月。

首先使用map2为每行数据在激活和到期之间创建一个月序列。这样,您就可以按月/年分组以计算每个月的活动策略数。

library(tidyverse)
library(lubridate)

df %>%
  mutate(month = map2(floor_date(activation_dt,"month"),floor_date(expiry_dt,seq.Date,by = "month")) %>%
  unnest(month) %>%
  transmute(month_year = substr(month,1,7)) %>%
  group_by(month_year) %>%
  summarise(count = n())

输出

   month_year count
   <chr>      <int>
 1 2020-01        4
 2 2020-02        6
 3 2020-03       10
 4 2020-04       10
 5 2020-05       10
 6 2020-06       10
 7 2020-07       10
 8 2020-08        7
 9 2020-09        6
10 2020-10        3
11 2020-11        2