在R语言的data.table中按可变日期范围重复行
用data.table按日期范围展开数据行
给定包含StartDate和StopDate的data.table,要将每行数据按日期范围展开,生成该范围内每天对应的行,保留其他列并新增Date列,可通过以下data.table的分组操作实现:
原始数据
library(data.table) input = data.table( X = c('John','John','Peter'), Age = c(20,25,12), StartDate = as.Date(c('2022-01-20','2018-12-03','2023-01-05')), StopDate = as.Date(c('2022-01-23','2018-12-07','2023-01-05')) )
原始数据表格:
| X | Age | StartDate | StopDate |
|---|---|---|---|
| John | 20 | 2022-01-20 | 2022-01-23 |
| John | 25 | 2018-12-03 | 2018-12-07 |
| Peter | 12 | 2023-01-05 | 2023-01-05 |
解决方案代码
# 按日期范围展开数据 output = input[, .(Date = seq(StartDate, StopDate, by = "day")), by = .(X, Age)]
输出结果
运行后得到的output结构如下:
| X | Age | Date |
|---|---|---|
| John | 20 | 2022-01-20 |
| John | 20 | 2022-01-21 |
| John | 20 | 2022-01-22 |
| John | 20 | 2022-01-23 |
| John | 25 | 2018-12-03 |
| John | 25 | 2018-12-04 |
| John | 25 | 2018-12-05 |
| John | 25 | 2018-12-06 |
| John | 25 | 2018-12-07 |
| Peter | 12 | 2023-01-05 |
代码说明
by = .(X, Age):指定分组依据,确保每一行的X和Age信息被保留到展开后的每一行中seq(StartDate, StopDate, by = "day"):生成从StartDate到StopDate的每日日期序列,作为新的Date列- data.table的分组操作会自动将每个分组的日期序列与分组列组合,生成最终展开后的数据集
内容的提问来源于stack exchange,提问作者Maddy
相关产品推荐
相关产品推荐

