Sum Blocks of Positive Values in R

We can use rleid to create a group based on the sign of the column i.e. same adjacent sign elements will be a single group and then get the max of the ‘cum_profit’

library(dplyr)
dat %>% 
    group_by(grp = rleid(sign(profit))) %>% 
     mutate(profit_block2 = max(cum_profit)) %>%
     ungroup %>%
     select(-grp)

-output

# A tibble: 10 x 5
#   profit indic_pos cum_profit profit_block profit_block2
#    <dbl>     <dbl>      <dbl>        <dbl>         <dbl>
# 1     20         1         20           45            45
# 2     10         1         30           45            45
# 3      5         1         35           45            45
# 4     10         1         45           45            45
# 5    -20         0          0            0             0
# 6   -100         0          0            0             0
# 7    -40         0          0            0             0
# 8    500         1        500          527           527
# 9     27         1        527          527           527
#10    -20         0          0            0             0

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top