Created
July 3, 2020 13:33
-
-
Save TimTeaFan/a1437ee6c4a6a05f6d41c17f9df380cd to your computer and use it in GitHub Desktop.
Calculate Head Count over Month based on start / end date.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(tidyverse) | |
library(lubridate) | |
dat <- tribble(~id, ~start, ~end, | |
0102, "2018-01-02", "2018-01-07", | |
2190, "2018-01-01", "2018-03-06", | |
2432, "2018-01-03", "2018-05-07", | |
0121, "2018-01-03", "2018-02-04", | |
0121, "2018-01-02", "2018-01-15", | |
) | |
tibble(data = list(dat)) %>% | |
crossing(month = seq(min(as.Date(dat$start)), | |
max(as.Date(dat$end)), | |
by = "+1 month")) %>% | |
rowwise(month) %>% | |
mutate(filter(data, | |
floor_date(as.Date(start), "months") <= .env$month, | |
as.Date(end) > .env$month) %>% | |
count) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment