【问题标题】:How to find if a date is within a given time interval如何查找日期是否在给定的时间间隔内
【发布时间】:2019-03-15 21:20:55
【问题描述】:

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

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],但没有帮助我。 谢谢!

【问题讨论】:

    标签: r dplyr lubridate


    【解决方案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 )
    

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

    【讨论】:

      猜你喜欢
      • 2018-07-26
      • 1970-01-01
      • 1970-01-01
      • 2020-09-18
      • 2022-11-11
      • 2017-10-27
      • 1970-01-01
      • 1970-01-01
      • 2011-02-07
      相关资源
      最近更新 更多