data <- data.frame(
record_id = c(1,1,1,2,3,4,4,5,6,7,8,8,9,10,10,10),
visit_date = c("2020-09-24", "2020-12-05", "2021-03-01", "2021-10-03", "2021-10-01", "2021-10-05", "NA", "2021-08-25", "2021-09-19", "2021-10-01", "2021-09-27", "2021-09-07",
"2021-10-03", "2021-10-08", "2022-03-22", "2022-07-12"),
repeat_instance = c(0,1,2,0,0,0,1,0,0,0,0,1,0,0,1,2),
Time_Since_Appointment = c("NA", "72d 1H 0M 0S", "86d 0H 0M 0S", "NA", "NA", "NA", "NA",
"NA", "NA", "NA", "NA", "1076d 0H 0M 0S", "NA", "NA", "165d 0H 0M 0S", "112d 0H 0M 0S")
)
data1 <- data %>%
group_by(record_id) %>%
mutate(Time_Since_Appointment = visit_date - lag(visit_date))
I am interested in calculating a new variable that would capture the number of days or weeks since today using the most recent repeat_instance, which differs for each record, or if there is not a repeat_instance calculates the time since the baseline visit date.
Thank you so much and please let me know if additional information should be supplied.