如何按组依次更新行

问题描述 投票:2回答:2

我有dt:

library(data.table)

DT <- data.table(a = c(1,2,3,4,5), b = c(4,5,6,7,8), c = c("X","X","X","Y","Y") ) 

我想在C列的每一组中添加一个d列:

  • 第一行值应与b[i]相同,
  • 每个组中的倒数第二行应为d[i-1] + 2*b[i]

预期结果:

   a b c d
1: 1 4 X 4
2: 2 5 X 14
3: 3 6 X 26
4: 4 7 Y 7
5: 5 8 Y 23

我试图使用诸如shift之类的功能,但是在这里我很难动态地更新行(可以这么说),想知道是否有任何优雅的data.table样式解决方案?

r data.table sequential rolling-computation
2个回答
3
投票

这里我们可以使用accumulate

library(purrr)
library(data.table)
DT[, d := accumulate(b, ~ .x + 2 *.y), by = c]

或使用Reduce中的accumulate = TRUEbase R

DT[, d := Reduce(function(x, y) x + 2 * y, b, accumulate = TRUE), by = c]

6
投票

我们可以使用cumsum并使用[1]减去第一行:

DT[, d := cumsum(2 * b) - b[1], .(c)][]

#>    a b c  d
#> 1: 1 4 X  4
#> 2: 2 5 X 14
#> 3: 3 6 X 26
#> 4: 4 7 Y  7
#> 5: 5 8 Y 23
© www.soinside.com 2019 - 2024. All rights reserved.