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

如何在R语言中将字符型时间数据转换为时间类型?

时间列转换与筛选的正确方式
  • 你用lubridate::hm()把字符格式的时间(比如"12:00")转成Period类型是可行的,但直接写filter(hours> "12H 0M 0S")不正确,因为R无法直接将字符串和Period对象进行比较。
  • 正确的操作有两种选择:
    1. 把用于比较的时间也转成Period类型:
      library(dplyr)
      library(lubridate)
      
      # 先转换原时间列
      df <- df %>% mutate(hours = hm(Time))
      # 筛选时间晚于12:00的数据
      df_filtered <- df %>% filter(hours > hm("12:00"))
      
    2. 将Period类型转换为数值型(比如总分钟数或小时数),筛选逻辑更直观:
      df <- df %>% mutate(
        hours = hm(Time),
        total_minutes = as.numeric(hours, "minutes") # 转换为总分钟数
      )
      # 筛选总分钟数大于720(即12小时)的数据
      df_filtered <- df %>% filter(total_minutes > 720)
      
  • 补充:如果你之前尝试chron::strptime失败,可能是没匹配对格式,用chron包处理可以更简单:
    library(chron)
    # 将"HH:MM"格式的字符直接转为chron时间类型
    df$time_chron <- times(df$Time)
    # 筛选晚于12:00的数据
    df_filtered <- df %>% filter(time_chron > times("12:00:00"))
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 01:55:11