我有一个数据帧(df)看起来像这样:
person | outcome | 1 |
---|---|
1 | |
0 | |
0 | |
0 | |
1 | |
0 | |
1 | |
1 | |
1 | |
0 | |
0 | |
0 |
也许这有帮助
library(dplyr)
df %>%
group_by(person) %>%
mutate(new = cumsum(outcome)) %>%
filter(if(last(outcome) == 0) new <max(new) else TRUE) %>%
ungroup %>%
select(-new)
与产出
# A tibble: 5 × 2
person outcome
<chr> <int>
1 a 1
2 b 1
3 b 0
4 b 1
5 c 1
数据df <- structure(list(person = c("a", "a", "a", "a", "a", "b", "b",
"b", "c", "c", "c", "c", "c"), outcome = c(1L, 1L, 0L, 0L, 0L,
1L, 0L, 1L, 1L, 1L, 0L, 0L, 0L)), class = "data.frame", row.names = c(NA,
-13L))