I have a df where I need to calculate the number of days between two types of events among a long list of possible events, say an overdose 'A_type_event' and a clinical session 'C_type_event' for a given unique id where event A always precedes event C:
df<- tribble(
~ unique_id, ~event_type, ~ event_date,
'id_101', 'A_type_event', '2022-01-01',
'id_101', 'B_type_event', '2022-02-01',
'id_101', 'A_type_event', '2022-02-15',
'id_101', 'A_type_event', '2022-02-28',
'id_101', 'B_type_event', '2022-03-01',
'id_101', 'C_type_event', '2022-03-10',
'id_101', 'A_type_event', '2022-03-20',
'id_101', 'C_type_event', '2022-04-01'
)
The actual df has 20+ event types and I need to filter based on a string (e.g., contains 'A_type'). How can I calculate the number of days between each 'A_type_event' and the next 'C_type_event' grouped by a unique id?
Desired output would be:
df2<- tribble(
~ unique_id, ~event_type_A, ~ event_date_A, ~event_type_C, ~event_date_C, ~days_between
'id_101', 'A_type_event', '2022-01-01','C_type_event', '2022-03-10',68
)