lubridate-计算每个间隔的重叠间隔 [英] lubridate - counting overlapping intervals for every interval

查看:86
本文介绍了lubridate-计算每个间隔的重叠间隔的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我今天在编程方面不是很有经验,但是过去很久以前做了一些工作.

i am not very experienced in programmming today, but did some work in the past far away.

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

We support shared cars and for every car there are bookings with a start-datetime and an end-datetime. Start-dt an end-dt for every booking is at full 00 or 30 minutes and has a duration >= 30 Minutes.

现在我想看看同一地点有多少辆汽车,有多少辆汽车在重叠时间有预订.

Now we have many cars at the same place an i want to see, how many cars had a booking at overlapping times.

为此,我建立了一个时隙序列,两次之间的持续时间为30分钟.

For this i build a sequence of timeslots with a duration of 30 minutes between two times.

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)

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

Then for every timeslot i count the bookings, which overlap that timeslot. This code works:

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的方式来解决我的问题.

This takes a while an i think, that is not very r-like. Now, before i start to optimize this code, i will ask the community of more experienced people, if there is an r-like way to solve my problem.

最诚挚的问候 鲁迪格

推荐答案

不知道bookings看起来并不容易,但是这种逻辑应该起作用.当您用lubridate标记问题时,我用它发布了解决方案.

Without knowing how bookings look like it's not that easy, but this logic should work. As you tagged question with lubridate I posted solution with it.

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))

这篇关于lubridate-计算每个间隔的重叠间隔的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆