Skip to content

Instantly share code, notes, and snippets.

@TimTeaFan
Created July 3, 2020 13:33
Show Gist options
  • Save TimTeaFan/a1437ee6c4a6a05f6d41c17f9df380cd to your computer and use it in GitHub Desktop.
Save TimTeaFan/a1437ee6c4a6a05f6d41c17f9df380cd to your computer and use it in GitHub Desktop.
Calculate Head Count over Month based on start / end date.
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