R / lubridate: Calculate number of overlapping days between two periods

后端 未结 2 624
予麋鹿
予麋鹿 2021-01-16 11:56

I am trying to calculate the number of overlapping days between two time periods. One period is fixed in a start and end date, the other is recorded as start and end dates i

2条回答
  •  别那么骄傲
    2021-01-16 12:22

    I think you may be running into issues with max and min vs pmax and pmin:

    library(dplyr)
    
    df %>%
      mutate(overlap = pmax(pmin(my.end, end) - pmax(my.start, start) + 1,0))
    
           start        end overlap
    1 2018-07-15 2018-07-20  0 days
    2 2018-07-20 2018-08-05  5 days
    3 2018-08-15 2018-08-19  5 days
    4 2018-08-20 2018-09-15 12 days
    5 2018-09-01 2018-09-15  0 days
    

提交回复
热议问题