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

时间:2019-03-15 21:20:55

标签: dplyr lubridate

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

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 ::间隔(开始日期,结束日期)。实际上,我有一个包含400列的数据框。

  2. 日期列的名称(如果日期在相应的间隔内)。就像下面的输出

    ID  Within_Intrvl
    1   a_b  
    2   a  
    3   a_c
    

我已阅读此问题[link]的答案,但没有帮助我。 谢谢!

1 个答案:

答案 0 :(得分:1)

假设您的数据已经使用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 )

您可以根据需要设置“ Interior_Intrvl”列的格式,并确定要如何处理NAs

相关问题