如何查找日期是否在给定时间间隔内

How to find if a date is within a given time interval

我有以下带日期的数据框。

ID   start_date      end_date      Intrvl                    a_date           b_date          c_date
1     2013-12-01     2014-05-01    2013-12-01--2014-05-01    2014-01-01       2014-03-10      2015-03-10       
2     2016-01-01     2016-07-01    2016-01-01--2016-07-01    2014-02-01       NA              2016-02-01
3     2014-01-01     2014-07-01    2014-01-01--2014-07-01    2014-02-01       2016-02-01      2014-07-01    

我想知道,

  1. 如果 a_date、b_date 和 c_date 列中的日期在我使用计算的间隔期间内 lubridate::间隔(start_date,end_date)。实际上我有一个包含 400 列的数据框。

  2. 如果日期在相应的区间内,则为日期列的名称。像下面的输出

    ID  Within_Intrvl
    1   a_b  
    2   a  
    3   a_c
    

我已经阅读了这个问题的答案,但对我没有帮助。 谢谢!

假设您的数据已经用 lubridate 转换,

input<- df %>%
  mutate(start_date=ymd(start_date)) %>%
  mutate(end_date=ymd(end_date)) %>%
  mutate(a_date=ymd(a_date)) %>%
  mutate(b_date=ymd(b_date)) %>%
  mutate(c_date=ymd(c_date)) %>%
  mutate(Intrvl=interval(start_date, end_date)) 

您可以在 lubridate 中使用 %within% 运算符

result <- input %>%
  mutate(AinIntrvl=if_else(a_date %within% Intrvl,"a","")) %>%
  mutate(BinIntrvl=if_else(b_date %within% Intrvl,"b","")) %>%
  mutate(CinIntrvl=if_else(c_date %within% Intrvl,"c","")) %>%
  mutate(Within_Intrvl=paste(AinIntrvl,BinIntrvl,CinIntrvl,sep="_")) %>%
  select(-start_date,-end_date,-Intrvl,-a_date,-b_date,-c_date )

您可以根据需要设置 Within_Intrvl 列的格式,并决定如何处理 NA