假设您有一个包含“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 中执行此操作的最简单方法是什么?