我有一個 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
這是預期的輸出
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
首選 data.table 解決方案。
uj5u.com熱心網友回復:
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
使用reprex v2.0.2創建于 2022-11-07
編輯
dt[, countdown := .N:1 * !flag, by=rleid(flag)]
為簡潔起見。
uj5u.com熱心網友回復:
另一種data.table選擇
> cbind(dt, dt[, .(countdonwn = .N - seq(.N)), rev(cumsum(rev(flag)))][, 2])
date flag countdonwn
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/529059.html
標籤:r数据表
下一篇:無法將串列列轉換為R中的因子
