R 中正值的求和块

Sum Blocks of Positive Values in R

我有一个大数据集,15 万行,大小约为 11 MB。每行包含每小时的利润度量,可以是正数、负数或零。我正在尝试计算一个新变量,该变量等于每个正“块”的利润。希望这在下面的数据集中是不言自明的。

“利润”是输入变量。我可以得到接下来的两列,但无法求解 "profit_block"。任何帮助将不胜感激!

dat <- data.frame(profit = c(20, 10, 5, 10, -20, -100, -40, 500, 27, -20),
                  indic_pos = c( 1, 1, 1, 1, 0, 0, 0, 1, 1, 0),
                  cum_profit = c(20, 30, 35, 45, 0, 0, 0, 500, 527, 0),
                  profit_block = c(45, 45, 45, 45, 0, 0, 0, 527, 527, 0))

   profit indic_pos cum_profit profit_block
1      20         1         20           45
2      10         1         30           45
3       5         1         35           45
4      10         1         45           45
5     -20         0          0            0
6    -100         0          0            0
7     -40         0          0            0
8     500         1        500          527
9      27         1        527          527
10    -20         0          0            0

我发现下面的 post 非常有用,但我不能完全符合我的需要。再次感谢。

相关URL:

我们可以使用rleid根据列的sign创建一个组即相同的相邻符号元素将是一个组,然后得到max'cum_profit'

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

-输出

# 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