You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在R中基于时间区间生成24小时时段指示变量?

在R中生成时间区间的小时指示变量

核心思路

把字符串格式的时间转换为一天中的总分钟数,然后对每个小时窗口(00:00-01:00、01:00-02:00...23:00-24:00),判断原时间区间是否与该小时窗口存在交集,存在则标记为1,否则为0。

完整实现代码

# 原始数据框
timedf <- data.frame(startime = c("0105","0205","0230","0245","0245"),
                     endtime  = c("0130", "0330","0330", "0400", "0405"))

# 加载dplyr(可选,用基础R也可实现)
library(dplyr)

# 转换时间为总分钟数
timedf <- timedf %>%
  mutate(
    start_total = as.numeric(substr(startime, 1, 2)) * 60 + as.numeric(substr(startime, 3, 4)),
    end_total = as.numeric(substr(endtime, 1, 2)) * 60 + as.numeric(substr(endtime, 3, 4))
  )

# 生成24个小时指示变量
hour_indicators <- sapply(0:23, function(h) {
  h_window_start <- h * 60
  h_window_end <- (h + 1) * 60
  # 判断时间区间与当前小时窗口是否有交集
  as.integer(timedf$start_total < h_window_end & timedf$end_total > h_window_start)
})

# 给指示变量命名(匹配am/pm格式)
hour_names <- c(
  paste0("time_", 0:11, "am"),
  "time_12pm",
  paste0("time_", 1:11, "pm")
)
colnames(hour_indicators) <- hour_names

# 合并结果并清理中间变量
result <- cbind(timedf[, c("startime", "endtime")], hour_indicators)

结果验证

运行上述代码后,result的前几列与你给出的示例完全一致:

# 查看前8列
result[, 1:8]
#   startime endtime time_0am time_1am time_2am time_3am time_4am time_5am
# 1     0105    0130        0        1        0        0        0        0
# 2     0205    0330        0        0        1        1        0        0
# 3     0230    0330        0        0        1        1        0        0
# 4     0245    0400        0        0        1        1        0        0
# 5     0245    0405        0        0        1        1        1        0

关键逻辑说明

判断两个区间是否有交集的核心条件是:原区间的起始时间小于当前小时窗口的结束时间,且原区间的结束时间大于当前小时窗口的起始时间。这个逻辑能准确覆盖以下场景:

  • 时间区间完全落在某一小时内(如0105-0130属于1am)
  • 时间区间跨多个小时(如0205-0330覆盖2am和3am)
  • 时间区间刚好在小时节点结束(如0245-0400不覆盖4am,因为结束时间等于4am窗口的起始时间,无交集)
  • 时间区间跨过小时节点开始(如0245-0405覆盖4am,因为结束时间大于4am窗口的起始时间)

内容的提问来源于stack exchange,提问作者zjppdozen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 02:55:28