【发布时间】:2020-04-24 18:37:33
【问题描述】:
我有一个非常复杂的问题,我无法解决。
我有一个在 dplyr 中读取的数据框:
trans_id date type
9373 2019-09-29 6-months
9945 2019-08-15 3-months
9945 2019-11-13 3-months
9615 2019-12-28 3-months
11465 2019-07-13 3-months
11465 2019-10-11 3-months
可重现的例子:
library(tidyverse)
df <- data.frame(stringsAsFactors=FALSE,
id = c(9373, 9945, 9945, 9615, 11465, 11465),
date = c("2019-09-29", "2019-08-15", "2019-11-13", "2019-12-28",
"2019-07-13", "2019-10-11"),
type = c("6-months", "3-months", "3-months", "3-months", "3-months",
"3-months")) %>%
mutate(date = as.Date(date))
每个id 都是一个事务,发生在给定的date 上;每笔交易可以每 3 个月或 6 个月重复一次 - 如type 中所述。
我想扩展这些每月对应的交易,直到当前日期;这意味着第一笔交易 9373 必须重复 6 次,周期为 30 天(type == 6 个月),从 2019 年 9 月 29 日到当天(今天是 2020 年 1 月 7 日),又名将只有 4 次单月交易,因为最后两次必须发生。
对于 3 个月的交易也是如此,始终考虑开始日期和当前日期。
最终结果示例:
id date type
9373 2019-09-29 6-months # first 6-months cycle transaction
9373 2019-10-29 6-months
9373 2019-11-28 6-months
9373 2019-12-28 6-months
9945 2019-08-15 3-months #
9945 2019-09-14 3-months
9945 2019-10-14 3-months
9945 2019-11-13 3-months #
9945 2019-12-13 3-months
9615 2019-12-28 3-months #
非常感谢任何帮助!
【问题讨论】: