Would like compute the elapsed time between action A and action X. There is different logic for other actions (B,C etc.) but they involve doing similar time differences.
Is there a way to use computed value for offset in shift? I have used shift in the past for fixed offset e.g. using lag to go back 12 rows within a group but can't figure how to incorporate conditional offset in shift
Here's a made up example:
x <- data.table(Case = c(1,1,1,1,2,2,2,3,3,3,3,3), Action = c("A","B","C","X","A","X","X","A","C","X","A","X"), ActionTime = parse_date_time(c("1/23/2020 12:55","1/26/20 3:23","1/28/2020 4:23","4/16/2020 17:50","1/25/2020 23:04","2/12/2020 17:50","2/13/2020 17:50","1/26/2020 3:23","2/18/2020 21:23","2/18/2020 21:27","3/15/2020 3:23","3/18/2020 21:27"), orders=c('mdy HM')))
setkeyv(x, c("Case", "ActionTime"))
> x
Case Action ActionTime
1: 1 A 2020-01-23 12:55:00
2: 1 B 2020-01-26 03:23:00
3: 1 C 2020-01-28 04:23:00
4: 1 X 2020-04-16 17:50:00
5: 2 A 2020-01-25 23:04:00
6: 2 X 2020-02-12 17:50:00
7: 2 X 2020-02-13 17:50:00
8: 3 A 2020-01-26 03:23:00
9: 3 C 2020-02-18 21:23:00
10: 3 X 2020-02-18 21:27:00
11: 3 A 2020-03-15 03:23:00
12: 3 X 2020-03-18 21:27:00
Case 1 is the simple case, Case 2 when Action X shows multiple times but I need the min value of time and Group 3 where A and X show multiple times within the same case.
I am looking to get XTime = the timestmp of the closest X after the occurrence of A within the case:
Case Action ActionTime XTime
1: 1 A 2020-01-23 12:55:00 2020-04-16 17:50:00
2: 1 B 2020-01-26 03:23:00
3: 1 C 2020-01-28 04:23:00
4: 1 X 2020-04-16 17:50:00
5: 2 A 2020-01-25 23:04:00 2020-02-12 17:50:00
6: 2 X 2020-02-12 17:50:00
7: 2 X 2020-02-13 17:50:00
8: 3 A 2020-01-26 03:23:00 2020-02-18 21:27:00
9: 3 C 2020-02-18 21:23:00
10: 3 X 2020-02-18 21:27:00
11: 3 A 2020-03-15 03:23:00 2020-03-18 21:27:00
12: 3 X 2020-03-18 21:27:00
Appreciate any help
Thanks