lubridate - 计算每个间隔的重叠间隔

lubridate - counting overlapping intervals for every interval

我今天的编程经验不是很丰富,但在过去很远的地方做过一些工作。

我们支持共享汽车,每辆车都有开始日期时间和结束日期时间的预订。每个预订的 Start-dt 和 end-dt 都是完整的 00 或 30 分钟,并且持续时间 >= 30 分钟。

现在我们有很多车在同一个地方,我想看看有多少辆车在重叠时间预订。

为此,我构建了一系列时隙,两次之间持续时间为 30 分钟。

library(dplyr)
TimeSlot =
   tibble(seq(
     from = as.POSIXlt("2013-07-01"),
     to = as.POSIXlt("2013-12-01"),
     1800 ))
 TimeSlot <- cbind(TimeSlot, c(0L))
 colnames(TimeSlot) <- c("Slot", "count")
 TimeSlot$count <- as.integer(TimeSlot$count)

然后对于每个时间段,我都会计算与该时间段重叠的预订。此代码有效:

for(j in 1:length(TimeSlot$count))
{
   for (i in 1:length(bookings$start)) {
     if ((TimeSlot[j, "Slot"] >= bookings[i, "start"]) &&
         (TimeSlot[j, "Slot"] < bookings[i, "end"])) {
       TimeSlot[j, "count"] = TimeSlot[j, "count"] + 1
       # rk_j = j
     }
   }
 }

我得到了结果。

这需要一段时间,我认为这不太像 r。现在,在我开始优化这段代码之前,我会询问社区中更有经验的人,是否有类似 r 的方法来解决我的问题。

此致 吕迪格

不知道 bookings 看起来并不那么容易,但这个逻辑应该可行。当你用 lubridate 标记问题时,我用它发布了解决方案。

library(lubridate)

# Transform time for Slot using lubridate
TimeSlot$Slot <- ymd_hms(TimeSlot$Slot)

# Create example dataset for bookings
bookings <- data.frame(start = c(TimeSlot$Slot[4], TimeSlot$Slot[12]), 
                       end   = c(TimeSlot$Slot[10], TimeSlot$Slot[22]))
# Transform booking to time interval
bookingsInterval <- interval(bookings$start, bookings$end)

# For each time slot sum how many overlaps with bookings interval
TimeSlot$count <- sapply(TimeSlot$Slot, function(x) sum(x %within% bookingsInterval))