r-如何计算表中两个间隔之间的时间重叠量



我想计算表中不同行的时间间隔之间的时间量。下面是data.frame的一个示例:

x <-tibble(name = c("Person1", "Person2", "Person3", "Person4"),
group = c("A", "A", "B", "B"),
start = c("2020-10-01-10:00", "2020-10-01-12:00", "2020-10-01-16:00", "2020-10-01-16:00"),
end = c("2020-10-01-16:00", "2020-10-01-18:00", "2020-10-01-20:00", "2020-10-01-23:00")) %>%
mutate(start = lubridate::ymd_hm(start),
end = lubridate::ymd_hm(end)) %>%
mutate(time_interval = interval(start = start, end = end))

我想生成另一列,显示每组中Persons的time_intervals重叠的小时数。我已经找过类似的问题和函数,但没有找到。R中是否有计算时间重叠的方法?

问候

间隔之间的重叠不是最近开始时间和最早结束时间之间的差异吗(如果有重叠(?这可以这样计算。如果没有重叠(="负"重叠(,则返回0。

require(lubridate)
x %>%
group_by(group) %>%
mutate(overlap = if_else(condition = max(start) < min(end), 
true = min(end) - max(start), 
false = 0))
# A tibble: 4 x 6
# Groups:   group [2]
name    group start               end                 time_interval                                    overlap
<chr>   <chr> <dttm>              <dttm>              <Interval>                                       <drtn> 
1 Person1 A     2020-10-01 10:00:00 2020-10-01 16:00:00 2020-10-01 10:00:00 UTC--2020-10-01 16:00:00 UTC 4 hours
2 Person2 A     2020-10-01 12:00:00 2020-10-01 18:00:00 2020-10-01 12:00:00 UTC--2020-10-01 18:00:00 UTC 4 hours
3 Person3 B     2020-10-01 16:00:00 2020-10-01 20:00:00 2020-10-01 16:00:00 UTC--2020-10-01 20:00:00 UTC 4 hours
4 Person4 B     2020-10-01 16:00:00 2020-10-01 23:00:00 2020-10-01 16:00:00 UTC--2020-10-01 23:00:00 UTC 4 hours

相关内容

  • 没有找到相关文章

最新更新