I am new to R. I am trying to delete prior rows based on conditions set by another column.
I have found solutions with dplyr and data.table which I believe to be close to what I am looking for, as they do the opposite.
Sample data:
Cust_ID | Date | Value
500219 | 2016-04-11 12:00:00 | 0
500219 | 2016-04-12 16:00:00 | A
500219 | 2016-04-14 11:00:00 | A
500219 | 2016-04-15 12:00:00 | B
500219 | 2016-05-23 09:00:00 | B
500219 | 2016-05-02 19:00:00 | C
500220 | 2016-04-11 12:00:00 | C
500220 | 2016-04-14 11:00:00 | C
500220 | 2016-04-15 12:00:00 | A
500220 | 2016-05-23 09:00:00 | A
500220 | 2016-05-02 19:00:00 | A
For each Cust_ID, I would like to retain only the rows after Value == "A" including that row. This should result in the following data frame:
Cust_ID | Date | Value
500219 | 2016-04-12 16:00:00 | A
500219 | 2016-04-14 11:00:00 | A
500219 | 2016-04-15 12:00:00 | B
500219 | 2016-05-23 09:00:00 | B
500219 | 2016-05-02 19:00:00 | C
500220 | 2016-04-15 12:00:00 | A
500220 | 2016-05-23 09:00:00 | A
500220 | 2016-05-02 19:00:00 | A
These are the solution I have already found (R delete rows based on values in previous rows)
library(data.table)
setDT(df1)[df1[, if(any(Value == "A")) .I[seq(max(which(Value == "A")))]
else .I[1:.N] , by = Cust_ID]$V1]
library(dplyr)
df1 %>%
group_by(Cust_ID) %>%
slice(if(any(Value=="A")) seq(max(which(Value=="A"))) else row_number())