Hi I have this dataset:
Data_List <- "I611|I613|I614|I639"
df <-
read.table(textConnection("ID Code Date1 Date2
A I611 01/01/2021 03/01/2021
A L111 04/01/2021 09/01/2021
B L111 01/01/2021 03/01/2021
B Z538 08/01/2021 11/01/2021
C I613 09/08/2021 09/09/2021
C I639 10/09/2021 18/09/2021
C I639 19/11/2021 22/11/2021
D L111 01/01/2021 02/01/2021
D I639 03/01/2021 04/01/2021
D B111 11/01/2021 14/01/2021"), header=TRUE)
What I am looking to do is filter rows where 'Code' value is within Data_List and the value in the row immediately below it for 'Date1' column is within 30 days of the value in Date2 column of original row (the row that matches its 'Code' value in Data_List). If these conditions are matched, both rows should be kept (and any subsequent rows where these conditions are matched for each grouped ID).
So from the above dataset we would end up with the below:
| ID | Code | Date1 | Date2 |
|---|---|---|---|
| A | I611 | 01/01/2021 | 03/01/2021 |
| A | L111 | 04/01//2021 | 09/01/2021 |
| C | I613 | 09/08/2021 | 09/09/2021 |
| C | I639 | 10/09/2021 | 18/09/2021 |
| D | I639 | 03/01/2021 | 04/01/2021 |
| D | B111 | 11/01/2021 | 14/01/2021 |
So for ID A we have 2 retained records as first record is a match to Data_List for 'Code' value and below column Date1 is within 30 days of the first record's Date2 so both are retained.
For ID B we have no retained records as there are only two records and the first record is not within Data_List for 'Code' value.
For ID C we have 2 retained records as first record is a match within Data_list for 'Code' and second is within 30 days for Date1 of the Date2 value in first record. The third ID = 'C' record is not retained as its Date1 value is not within 30 days of Date2 in record above it.
For ID D we again have 2 matches but this is for the 2nd and 3rd rows which apply, thus demonstrating that sometimes the 'loop' does not start on row 1.
If anyone could assist with this filtering that would be very much appreciated, thank you.