Specifically, I have a data
look like this:
counter
1
2
3
1
1
2
3
4
5
6
and I am looking for a new_column
that can get the max value rowwise until it hit 1, which reset the whole process.
counter | new_column
1 | 3
2 | 3
3 | 3
1 | 1
1 | 6
2 | 6
3 | 6
4 | 6
5 | 6
6 | 6
How to achieve that in R/dplyr
?
CodePudding user response:
Here's a straightforward solution:
library(dplyr)
df %>%
group_by(group = cumsum(counter == 1)) %>%
mutate(max = max(counter)) %>%
ungroup() %>%
select(-group)
# # A tibble: 10 × 2
# counter max
# <dbl> <dbl>
# 1 1 3
# 2 2 3
# 3 3 3
# 4 1 1
# 5 1 6
# 6 2 6
# 7 3 6
# 8 4 6
# 9 5 6
#10 6 6