如果 r 中的值变为负数,则重置 cumsum

标签 r dplyr conditional-statements cumsum

ve <- c(17, -9, 9, -17, 17, -17, 11, -9, 16, -18, 17, 0, 0, -18, 17, 0, 0, -17, 14, -14, 17, -2, 0, -15, 9, -9, 17, -16, 16, -17, 17, -17, 17, -17, 17, -17, 17, -8, 7, -16, 17, -14, 14, -10, 10, -16, 16, -10, 10, -12, 12, -11, 11, -17, 17, -17, 17, -9, 8, -17, 17, -17, 17, -16, 16, -17, 17, -8, 8, -9, 9, -17, 17, -17, 17, -13, 13, -10, 7, -10, 13, -16, 17, -13, 13, -13, 13, -9, 8, -17, 17, -10, 9, -17, 17, -17, 17, -16, 16, -10, 10, -15, 15, -14, 14, -14, 15, -13, 13, -9, 9, -13, 13, -12, 12, -10, 9, -11, 12, -8, 7, -10, 10, -9, 9, -11, 11, -9, 9, -7, 7, -12, 11, -11, 12, -11, 11, -14, 14, -13, 13, -10, 10, -13, 13, -17, 17, -7, 7, -17, 17, -17, 17, -14, 14, NA)

df <- data.frame(ve = ve, calc = 0)

我需要计算列 calc 中的 cumsum,但它需要重置为零并在其值为负时重新开始。
我已经尝试了几种条件,但它并没有真正起作用......

另外,是否可以在 dplyr 中实现这一点?我是 dplyr 的新手,每当我需要使用依赖值时都会发现它有点困难。

感谢您的帮助!

它应该像..
     ve calc
1    17    17
2    -9    8
3     9    17
4   -17    0
5    17    17
6   -17    0
7    11    11
8    -9    2
9    16    18
10  -18    0
11   17    17
12    0    17
13    0    17
14  -18    0
15   17    17

如果您看到第 14 行和第 15 行,则正常累积总和将为 -1 和 16
但我希望它重置为 0 而不是 -1 并继续 cumsum,因此下一个将是 17

最佳答案

我们可以replace NA 值为 0 并使用 cumsum

library(dplyr)
df1 <- df %>%
      group_by(grp = cumsum(lag(cumsum(replace(ve, is.na(ve), 0)) < 0, default = TRUE))) %>%
     mutate(calc = cumsum(replace(ve, is.na(ve), 0)), calc = replace(calc, calc < 0, 0)) %>%
      ungroup() %>%
      select(-grp)
head(df1, 15)
# A tibble: 15 x 2
#      ve  calc
#   <dbl> <dbl>
# 1    17    17
# 2    -9     8
# 3     9    17
# 4   -17     0
# 5    17    17
# 6   -17     0
# 7    11    11
# 8    -9     2
# 9    16    18
#10   -18     0
#11    17    17
#12     0    17
#13     0    17
#14   -18     0
#15    17    17

关于如果 r 中的值变为负数,则重置 cumsum,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44512075/

相关文章:

r - 在 R 中使用带有条件的 ifelse 进行变异

R/dplyr : Using a loop to create lags and calculate cumulative sums based on column names

javascript - 条件运算符 "? : "可以被视为 JavaScript 中 if-else 语句的替代吗?

r - 将字符串转换为 R 中的函数

r - 如何根据关联条件在 dplyr 中进行过滤

r - R : Replace a column value with a value from same column after matching two other columns values 中的数据表

r - 如何在 R 中构建一次汇总多个值的表

R:了解 mutate_ 中的标准评估

php - if else 条件不适用于 php 中的数组值

java - 需要计数值为0表示显示输出