简体   繁体   English

如何获取列的最大值,当该列中的某个值在R中满足时重置最大值

[英]How to get the max value of a column, reset the max value when certain value in this column is meet in R

Specifically, I have a data look like this:具体来说,我有一个如下所示的data

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.我正在寻找一个new_column可以按行获得最大值,直到它达到 1,这会重置整个过程。

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 ?如何在R/dplyr实现?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM