根据开始日期创建重叠的日期向量。

问题描述 投票:1回答:1

只是想看看是否有更直观的方法来做这件事。我需要从一个特定的开始日期,到当前日期,创建重叠的日期间隔。例如,我的第一个区间是(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  

两个问题:

  1. 有没有更好的方法?
  2. 为什么会返回新农合,如何才能放弃?

谢谢大家

r date lubridate
1个回答
0
投票

lubridate有一个间隔函数。请参考。https:/cran.r-project.orgwebpackageslubridatevignetteslubridate.html。

例子

library(lubridate)

t <- as.POSIXct("2019-01-01", tz = "UTC")
n <- 16
arrive <- seq(t, by = "month", length.out = n)
depart <- tail(seq(t, by = "month", length.out = n+2), -2)
interval(arrive, depart)

结果

 [1] 2019-01-01 UTC--2019-03-01 UTC 2019-02-01 UTC--2019-04-01 UTC
 [3] 2019-03-01 UTC--2019-05-01 UTC 2019-04-01 UTC--2019-06-01 UTC
 [5] 2019-05-01 UTC--2019-07-01 UTC 2019-06-01 UTC--2019-08-01 UTC
 [7] 2019-07-01 UTC--2019-09-01 UTC 2019-08-01 UTC--2019-10-01 UTC
 [9] 2019-09-01 UTC--2019-11-01 UTC 2019-10-01 UTC--2019-12-01 UTC
[11] 2019-11-01 UTC--2020-01-01 UTC 2019-12-01 UTC--2020-02-01 UTC
[13] 2020-01-01 UTC--2020-03-01 UTC 2020-02-01 UTC--2020-04-01 UTC
[15] 2020-03-01 UTC--2020-05-01 UTC 2020-04-01 UTC--2020-06-01 UTC

或者,如果不使用Lubridate,简单的粘贴就可以创建出和你描述的一样的字符向量。

paste(format(arrive, "%F"), format(depart, "%F"), sep = " ")

结果

 [1] "2019-01-01 2019-03-01" "2019-02-01 2019-04-01" "2019-03-01 2019-05-01"
 [4] "2019-04-01 2019-06-01" "2019-05-01 2019-07-01" "2019-06-01 2019-08-01"
 [7] "2019-07-01 2019-09-01" "2019-08-01 2019-10-01" "2019-09-01 2019-11-01"
[10] "2019-10-01 2019-12-01" "2019-11-01 2020-01-01" "2019-12-01 2020-02-01"
[13] "2020-01-01 2020-03-01" "2020-02-01 2020-04-01" "2020-03-01 2020-05-01"
[16] "2020-04-01 2020-06-01"
© www.soinside.com 2019 - 2024. All rights reserved.