![](/img/trans.png)
[英]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.