Skip to content

Instantly share code, notes, and snippets.

@Lextuga007
Created May 1, 2021 17:19
Show Gist options
  • Select an option

  • Save Lextuga007/38c90559c600843ebf5eee774b4a9836 to your computer and use it in GitHub Desktop.

Select an option

Save Lextuga007/38c90559c600843ebf5eee774b4a9836 to your computer and use it in GitHub Desktop.
Finding open referrals in a given period
library(lubridate)
library(tidyverse)
# create random start and end dates and ids which can be repeated
data <- data.frame(
start_date = sample(seq(as.Date('2019/01/01'), as.Date('2021/01/01'), by = "day"), 300),
end_date = sample(seq(as.Date('2019/01/01'), as.Date('2021/01/01'), by = "day"), 300),
patient_id = floor(runif(300, min = 1, max = 300))
)
# remove where the end date is before the start date and add referral numbers as patients have multiple
# referrals
data_filtered <- data %>%
filter(end_date > start_date) %>%
group_by(patient_id) %>%
mutate(referral_id = row_number(start_date))
# Create an observation for every date between the start and end date
data_expanded <- data_filtered %>%
group_by(patient_id,
referral_id) %>%
pivot_longer(cols = ends_with("date"),
names_to = "caseload",
values_to = "dates") %>%
complete(dates = seq.Date(min(dates), max(dates), by="day")) %>%
ungroup() # affects any counts or summarising later
data_counted <- data_expanded %>%
mutate(year = lubridate::year(dates)) %>%
group_by(year) %>%
summarise(count = n_distinct(patient_id, referral_id))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment