library(tidyverse)
date.end.month <- seq(from = as.Date("2009-01-01"), to = as.Date("2020-03-01"), by = "months")-1
bill_dev <- function(theDate) {
df %>%
filter(BILL_DT>='2009-01-01') %>%
group_by(CUSTOMER) %>%
filter(
BILL_DT <= theDate,
DELIVERY_DT >= theDate | is.na(DELIVERY_DT)
) %>%
summarize(sumiv=sum(UNITS),
DATE= format(theDate, "%Y-%m"))
}
do.call(rbind, lapply(date.end.month, bill_dev)) %>%
arrange(CUSTOMER, DATE) %>%
print(n=32)
Выход
# A tibble: 32 x 3
CUSTOMER sumiv DATE
<chr> <int> <chr>
1 A 1 2012-11
2 A 1 2012-12
3 A 1 2013-01
4 A 1 2018-09
5 A 1 2018-10
6 A 1 2018-11
7 A 1 2018-12
8 A 1 2019-01
9 A 1 2019-02
10 A 1 2019-03
11 A 1 2019-04
12 B 1 2017-11
13 B 1 2017-12
14 B 1 2018-01
15 B 1 2018-02
16 B 1 2018-03
17 B 3 2018-04
18 B 1 2018-05
19 B 1 2018-06
20 B 1 2018-07
21 B 1 2018-08
22 B 1 2018-09
23 B 1 2019-06
24 B 1 2019-07
25 B 1 2019-08
26 B 1 2019-09
27 B 1 2019-10
28 C 1 2018-03
29 C 1 2018-04
30 C 1 2018-05
31 C 1 2018-06
32 C 1 2018-07
Данные
df <- structure(list(CUSTOMER = c("A", "A", "A", "A", "A", "B", "B",
"B", "B", "C", "C", "C"), BILL_DT = structure(c(13854, 15665,
8380, 17780, 12751, 12110, 17483, 17628, 18065, 17669, 17606,
13504), class = "Date"), DELIVERY_DT = structure(c(14187, 15736,
8538, 18044, 13063, 12499, 17823, 17669, 18225, 17754, 17681,
13742), class = "Date"), UNITS = c(1L, 1L, 1L, 1L, 1L, 1L, 1L,
2L, 1L, 1L, 1L, 1L)), row.names = c(NA, -12L), class = "data.frame")