请尝试以下操作。
filter(df, cumsum(test.result)<=1
& test.result==cummax(test.result), .by=ID)
ID seq test.result
1 1 1 1
2 2 1 0
3 2 2 1
4 3 1 0
5 3 2 0
6 3 3 0
7 3 4 1
数据
df
ID seq test.result
1 1 1 1
2 1 2 0
3 1 3 1
4 1 4 0
5 1 5 0
6 2 1 0
7 2 2 1
8 2 3 0
9 2 4 0
10 3 1 0
11 3 2 0
12 3 3 0
13 3 4 1
df <- structure(list(ID = c(1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3),
seq = c(1, 2, 3, 4, 5, 1, 2, 3, 4, 1, 2, 3, 4), test.result = c(1,
0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1)), class = "data.frame", row.names = c(NA,
-13L))