日期 %within% 间隔

Dates %within% Intervals

运行 真是令人头疼,不知如何解决。真的希望你们中的一些人能够提供帮助。另外,这是我第一次为 Whosebug 做出贡献....耶!

library(tidyverse)
library(lubridate)

start_date <- ymd("2014-06-28")
end_date <- ymd("2019-06-30")
PayPeriod_EndDate <- seq(start_date, end_date, by = '2 week')
PayPeriod_Interval <- int_diff(PayPeriod_EndDate)

这将创建一个间隔向量,每个间隔代表两周的支付期。这是第一部分,第一部分相对容易(虽然还是花了点时间才弄明白,哈)。

第二部分包含一个日期向量。

Dates <- c("2014-07-08", "2018-10-20", "2018-12-13", "2018-12-13", "2018-12-06", "2018-11-30", "2019-01-16", "2019-01-23", "2019-03-15", "2018-10-02")

我想用输出来识别日期%within%间隔是每个日期所处的时间间隔。因此日期 "2014-07-08" 将被分配 2014-06-28 UTC--2014-07-12 UTC,因为此日期在此间隔内。

这里似乎已经探讨了一个非常相似的问题...https://github.com/tidyverse/lubridate/issues/658

我尝试了以下

ymd(Dates) %within% PayPeriod_Interval

但是,结果仅计算 Dates 向量中的第一个元素。从那以后,我尝试了 for 循环的各种组合,变异为因子等……但进展甚微。这是与工作相关的,所以我真的很赶时间,我会全天监控这个 post 直到周末。

最好,谢谢! 詹姆斯

tidyverse 非常有用,但有时,基础 R 就足够了。在这种情况下,cut 函数就是您所需要的。

library(lubridate)

start_date <- ymd("2014-06-28")
end_date <- ymd("2019-06-30")
PayPeriod_EndDate <- seq(start_date, end_date, by = '2 week')

Dates <- c("2014-07-08", "2018-10-20", "2018-12-13", "2018-12-13", "2018-12-06", "2018-11-30", "2019-01-16", "2019-01-23", "2019-03-15", "2018-10-02")


startperiod<-cut(as.Date(Dates), breaks=PayPeriod_EndDate)
endperiod<-as.Date(startperiod)+13

cut函数的输出是"Dates"变量所在的每个支付期的开始日期。

这就是 map - 解决方案的样子:

map(ymd(Dates), ~ PayPeriod_Interval[.x %within% PayPeriod_Interval])
# [[1]]
# [1] 2014-06-28 UTC--2014-07-12 UTC
# 
# [[2]]
# [1] 2018-10-13 UTC--2018-10-27 UTC
# 
# ...

要将结果作为区间向量(而不是列表),您可以使用:

PayPeriod_Interval[map_int(ymd(Dates), ~ which(.x %within% PayPeriod_Interval))]

# [1] 2014-06-28 UTC--2014-07-12 UTC 2018-10-13 UTC--2018-10-27 UTC 2018-12-08 UTC--2018-12-22 UTC 2018-12-08 UTC--2018-12-22 UTC 2018-11-24 UTC--2018-12-08 UTC
# [6] 2018-11-24 UTC--2018-12-08 UTC 2019-01-05 UTC--2019-01-19 UTC 2019-01-19 UTC--2019-02-02 UTC 2019-03-02 UTC--2019-03-16 UTC 2018-09-29 UTC--2018-10-13 UTC

如果您只对间隔的结束日期感兴趣,一个选项是

PayPeriod_EndDate[map_int(ymd(Dates), ~ which.min(.x > PayPeriod_EndDate))]
# [1] "2014-07-12" "2018-10-27" "2018-12-22" "2018-12-22" "2018-12-08" "2018-12-08" "2019-01-19" "2019-02-02" "2019-03-16" "2018-10-13"

which.min returns PayPeriod_EndDate 的第一个日期条目的编号,该日期不小于日期向量中的特定日期,因此日期位于特定付款期结束。