[英]R: sum negative values in a vector only if they are preceded by positive values
[英]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
我发现下面的帖子非常有帮助,但我不能完全符合我的需要。 再次感谢。
我们可以使用rleid
根据列的sign
创建一个组,即相同的相邻符号元素将成为一个组,然后获得 'cum_profit' 的max
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.