【发布时间】:2020-05-01 21:50:24
【问题描述】:
只是想看看是否有更直观的方法可以做到这一点。我需要创建从特定开始日期到当前日期的重叠日期间隔。例如,我的第一个区间是 (2019-01-01 -- 2019-04-30),而我的下一个区间是 (2019-03-01 -- 2019-05-31),这样就有重叠至少1个月。
这是我的代码:
library(dplyr)
library(lubridate)
current_date <- today()
start_date <- as.Date("2019-01-01")
i <- NULL
interval_vector <- c() # to store
for(i in 1:length(months_sequence)){
# define end date (90 days)
end_date <- ceiling_date(start_date + (days(90)),unit = "month") - 1
interval_vector[[i]] <- paste0(start_date, " ", end_date)
# define new start date
start_date <- floor_date(end_date - days(30), unit = "month")
# drop future dates
interval_vector <- interval_vector[interval_vector < current_date]
# interval_vector <- interval_vector
}
interval_vector
结果如下:
[1] "2019-01-01 2019-04-30" "2019-03-01 2019-05-31" "2019-05-01 2019-07-31" "2019-07-01 2019-09-30" "2019-08-01 2019-10-31"
[6] "2019-10-01 2019-12-31" "2019-12-01 2020-02-29" "2020-01-01 2020-03-31" "2020-03-01 2020-05-31" NA
[11] NA NA NA NA NA
[16] NA
两个问题:
- 有没有更好的方法来做到这一点?
- 为什么会返回 NA,如何删除它们?
谢谢大家
【问题讨论】: