【问题标题】:lubridate - counting overlapping intervals for every intervallubridate - 计算每个间隔的重叠间隔
【发布时间】:2017-09-15 13:02:18
【问题描述】:

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

我们支持共享汽车,每辆汽车都有带有开始日期时间和结束日期时间的预订。每个预订的开始-dt 和结束-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 的方法来解决我的问题。

最好的问候 吕迪格

【问题讨论】:

  • 我该怎么做?
  • 你能检查答案左边的绿色箭头吗,谢谢!

标签: r lubridate


【解决方案1】:

在不知道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))

【讨论】:

  • 太好了,谢谢。似乎它有效。我只需要看看,从 2015-10-01 12:00:00 到 2015-10-01 12:30:00 的预订是否与两个或一个插槽重叠。诀窍是 %within% ;-)
  • 如果元素数量与您想要的不匹配,您可以从预订中减去一分钟
  • 这是我的主意。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-03-22
  • 1970-01-01
  • 1970-01-01
  • 2020-02-19
  • 2022-10-05
  • 2021-07-23
  • 1970-01-01
相关资源
最近更新 更多