a <- c("A","A","A","B","B","B","C","C","C","C","D","D","D","D","D")
b <- c("x","y","z","x","x","z","y","z","z","z","y","z","z","z","x")
df = data.frame(a,b)
a b
1 A x
2 A y
3 A z
4 B x
5 B x
6 B z
7 C y
8 C z
9 C z
10 C z
11 D y
12 D z
13 D z
14 D z
15 D x
For each group A, B, C, D, I would like to delete the z value in column b each time the combination y, z appears at the end of the group.
If we have a case with == "C", where the b-values are y, z, z, z, I would like to delete all z. However, nothing should change in the "D" dialog, since x is the last value.
The results look like this:
a b
1 A x
2 A y
4 B x
5 B x
6 B z
7 C y
11 D y
12 D z
13 D z
14 D z
15 D x
By grouping in dplyr, I can determine the last occurrence of each value in A, so the main case depicted in a=="A"is not a problem. I find it difficult to find a solution for the case a=="C"where I could have one occurrence of y followed by 20 occurrences of z.