如果在 2 行中满足某些条件,如何在 R 数据框中添加新列以显示当前行和前一行中值的总和?

How to add new column in R data frame showing sum of a value in a current row and a prior row, if certain conditions are met in the 2 rows?

假设您有一个由“a”和“b”列组成的数据框,其值如下所示,由 df <- data.frame(a=c(0, 1, 2, 2, 3), b=c(1, 3, 8, 9, 4)) 生成。假设您要添加列“c”,如果“a”中的值等于“a”列中前一行的值,则将“b”列中相应行的值相加;否则显示 0 值。下面添加了一列“c”来说明我正在尝试做什么:

   a  b   add col c
1  0  1       0
2  1  3       0
3  2  8       0
4  2  9       17 (since the values in col "a" rows 3 and 4 are equal, add the values in col b rows 3 and 4)
5  3  4       0

或者在这种情况下,列“a”和“b”由 df <- data.frame(a=c(0,1,2,2,2,3), b=c(1,2,3,4,5,6)):

生成
   a  b    add col c
1  0  1        0
2  1  2        0
3  2  3        0
4  2  4        7 (3+4 from col "b")
5  2  5        9 (4+5 from col "b")
6  3  6        0 (since 2 from prior row <> 3 from current row)

在本机 R 中执行此操作的最简单方法是什么?

由于我们希望相邻值相等,因此使用 rleid(来自 data.table)创建分组索引,然后通过添加 'c' 创建 'c' =29=] 替换为 'b' 的 lag 并将 lag (NA) 的默认第一个值替换为 0

library(dplyr)
library(data.table)
library(tidyr)
df %>% 
   group_by(grp = rleid(a)) %>% 
   mutate(c = replace_na(b + lag(b), 0)) %>%
   ungroup %>%
   select(-grp)

-输出

# A tibble: 6 × 3
      a     b     c
  <dbl> <dbl> <dbl>
1     0     1     0
2     1     2     0
3     2     3     0
4     2     4     7
5     2     5     9
6     3     6     0

或使用 base R - 类似的方法是使用 rle 创建 'grp',然后使用 ave 将前一个值与当前值相加(通过删除第一个和最后一个)然后在开头附加 0

grp <- with(rle(df$a), rep(seq_along(values), lengths))
df$c <- with(df, ave(b, grp, FUN = function(x) c(0, x[-1] + x[-length(x)])))