I am stuck in writing this logic in R. Can someone help me to write this logic?
Logic:
(Priority1) For an Item, Date1 == Calendar then we have to select that row. Eg - Item B
(Priority2) For an Item if not Priority1 then, Date1 ~ Previous date in Calendar column then select that row. Eg - Item C
(Priority3) For an Item if not Priority1 & 2 then, Date1 ~ Next date in Calendar column then select that row. Eg - Item A
Input:
Item Date1 Calendar
A 2021-01-08 2021-01-11
A 2021-01-08 2021-01-19
B 2021-02-05 2021-01-29
B 2021-02-05 2021-02-05
B 2021-02-05 2021-02-12
C 2021-02-15 2021-02-07
C 2021-02-15 2021-02-13
C 2021-02-15 2021-02-20
C 2021-02-15 2021-02-27
This is the dput of the data
input <- structure(list(Item = c("A", "A", "B", "B","B", "C", "C","C","C"), Date1 = c("2021-01-08",
"2021-01-08", "2021-02-05", "2021-02-05", "2021-02-05", "2021-02-15", "2021-02-15", "2021-02-15", "2021-02-15"), Calendar = c("2021-01-11", "2021-01-19", "2021-01-29", "2021-02-05","2021-02-12", "2021-02-07","2021-02-13", "2021-02-20", "2021-02-27")), class = "data.frame", row.names = c(NA, -9L))
Output:
Item Date1 Calendar
A 2021-01-08 2021-01-11
B 2021-02-05 2021-02-05
C 2021-02-15 2021-02-13
This is the dput of the expected output.
output <- structure(list(Item = c("A","B", "C"), Date1 = c("2021-01-08","2021-02-05", "2021-02-15"), Calendar = c("2021-01-11","2021-02-05","2021-02-13")), class = "data.frame", row.names = c(NA, -3L))