按段数 (R) 分隔相交时间间隔

问题描述 投票:0回答:1

我正在研究时间间隔的数据集。有些间隔重叠。我想获取原始间隔数据,并按重叠次数将其分成连续的间隔。在下面的玩具数据中,有 3 个区间。我想要的输出是一个数据帧,其中包含只有一个 ID 的位置的开始和停止,然后是 ID 1 和 ID 2 相交的位置的开始和停止,然后是 ID 1-3 相交的位置的开始和停止,然后是 ID 1 和 ID 2 相交的位置的开始和停止,然后是 ID 1 和 ID 2 相交的位置的开始和停止。 ID 1 和 3 相交,最后是 ID 1 余数的开始和结束。

library(lubridate)
library(ggplot2)

df <- structure(list(ID = 1:3, Start = structure(c(1690740180, 1690740480, 
1690741380), class = c("POSIXct", "POSIXt"), tzone = "America/Iqaluit"), 
    End = structure(c(1690751520, 1690742140, 1690742280), class = c("POSIXct", 
    "POSIXt"), tzone = "America/Iqaluit")), row.names = 3:5, class = "data.frame")

ggplot(df) + geom_segment(aes(x = Start, xend = End, y = as.factor(ID), yend = as.factor(ID)))

所需的输出应如下所示:

  Intervals               Start                 End
         1 2023-07-30 14:03:00 2023-07-30 14:07:59
         2 2023-07-30 14:08:00 2023-07-30 14:22:59
         3 2023-07-30 14:23:00 2023-07-30 14:35:40
         2 2023-07-30 14:35:40 2023-07-30 14:38:00
         1 2023-07-30 14:38:00 2023-07-30 15:06:40

我可以通过将数据插值到 1 秒并检查交叉点来做到这一点,但我希望有一个更干净的解决方案。

r intervals lubridate
1个回答
0
投票

这是一个基本的 R 解决方案:

alltimes <- unique(sort(c(df$Start, df$End)))
intervals <- sapply(intervals[-length(intervals)], function(tm) df$Start <= tm & tm < df$End)
intervals
#       [,1]  [,2] [,3]  [,4]  [,5]
# [1,]  TRUE  TRUE TRUE  TRUE  TRUE
# [2,] FALSE  TRUE TRUE FALSE FALSE
# [3,] FALSE FALSE TRUE  TRUE FALSE
data.frame(
  Intervals = colSums(intervals),
  Start = alltimes[-length(alltimes)],
  End = alltimes[-1]
)
#   Intervals               Start                 End
# 1         1 2023-07-30 14:03:00 2023-07-30 14:08:00
# 2         2 2023-07-30 14:08:00 2023-07-30 14:23:00
# 3         3 2023-07-30 14:23:00 2023-07-30 14:35:40
# 4         2 2023-07-30 14:35:40 2023-07-30 14:38:00
# 5         1 2023-07-30 14:38:00 2023-07-30 17:12:00
© www.soinside.com 2019 - 2024. All rights reserved.