向 data.table 添加倒计时

Sau*_*abh 2 group-by r sequence data.table

我有一个 data.table,我想向其中添加倒计时,直到列中出现值 1 flag

dt = structure(list(date = structure(19309:19318, class = c("IDate", 
"Date")), flag = c(0, 0, 0, 0, 0, 1, 0, 0, 0, 1)), class = c("data.table", 
"data.frame"), row.names = c(NA, -10L), .internal.selfref = <pointer: 0x55af7de49cb0>)
> dt
          date flag
 1: 2022-11-13    0
 2: 2022-11-14    0
 3: 2022-11-15    0
 4: 2022-11-16    0
 5: 2022-11-17    0
 6: 2022-11-18    1
 7: 2022-11-19    0
 8: 2022-11-20    0
 9: 2022-11-21    0
10: 2022-11-22    1
Run Code Online (Sandbox Code Playgroud)

这是预期的输出

          date flag countdown
 1: 2022-11-13    0 5
 2: 2022-11-14    0 4
 3: 2022-11-15    0 3
 4: 2022-11-16    0 2
 5: 2022-11-17    0 1
 6: 2022-11-18    1 0
 7: 2022-11-19    0 3
 8: 2022-11-20    0 2
 9: 2022-11-21    0 1
10: 2022-11-22    1 0
Run Code Online (Sandbox Code Playgroud)

data.table 解决方案是首选。

Ric*_*Ric 7

data.table 解决方案不仅是首选,而且美观。

library(data.table)

dt = structure(list(date = structure(19309:19318, class = c("IDate", 
"Date")), flag = c(0, 0, 0, 0, 0, 1, 0, 0, 0, 1)), class = c( 
"data.frame"), row.names = c(NA, -10L))

setDT(dt)

dt[, countdown := rev(1:.N), by=rleid(flag)][flag==1, countdown:=0 ]
dt
#>           date flag countdown
#>  1: 2022-11-13    0         5
#>  2: 2022-11-14    0         4
#>  3: 2022-11-15    0         3
#>  4: 2022-11-16    0         2
#>  5: 2022-11-17    0         1
#>  6: 2022-11-18    1         0
#>  7: 2022-11-19    0         3
#>  8: 2022-11-20    0         2
#>  9: 2022-11-21    0         1
#> 10: 2022-11-22    1         0
Run Code Online (Sandbox Code Playgroud)

创建于 2022-11-07,使用reprex v2.0.2

编辑

dt[, countdown := .N:1 * !flag, by=rleid(flag)]
Run Code Online (Sandbox Code Playgroud)

为简洁起见。