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

RStudio中字符型小时转时分格式时间类的技术问询

问题:将字符型小时数据转换为时分格式时间类

我的数据集里的hours列是字符类型,值为00、01…23,对应0-23时。需要把它转换成仅含时分(比如00:00、01:00)的时间类型。数据集示例:

A tibble: 6 × 10
##   date       station hours AMB_TEMP    CO    NO   NO2   NOx    O3  PM10
##   <date>     <chr>   <chr>    <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
## 1 2015-01-01 Cailiao 00          16  0.74   1      15    16    35   171
## 2 2015-01-01 Cailiao 01          16  0.7    0.8    13    14    36   174
## 3 2015-01-01 Cailiao 02          15  0.66   1.1    13    14    35   160
## 4 2015-01-01 Cailiao 03          15  0.61   1.7    12    13    34   142
## 5 2015-01-01 Cailiao 04          15  0.51   2      11    13    34   123
## 6 2015-01-01 Cailiao 05          14  0.51   1.7    13    15    32   110

尝试过的无效方法

以下方法均未达到预期效果:

  • 直接用as.POSIXct转换:
cleantimedata <- timedata %>% 
  mutate(as.POSIXct(hours, format="%H%M"))
  • 尝试substr和paste拼接:
mutate(substr(hours, 0, nchar(hours)-2)) %>% 
mutate(paste0(hours, ':', mins))
  • 用strptime和strftime处理:
strftime(strptime(sapply(paste0(hours), function(i) substring(i, nchar(i) - 3, nchar(i))), "%H%M"), format = "%H:%M")
  • 转为数值型或直接用parse_time:
mutate(hours = parse_number(hours))
mutate(hours = parse_time(hours))
mutate(hours, as.numeric(hours)) 

当前非优雅解决方案

已实现需求但代码冗余:

clean_timedata <- timedata %>%
  mutate(hours = stri_pad_right(hours, 4, 0)) %>% 
  mutate(hours = gsub('(..)(?=.)', '\\1:', hours, perl=TRUE)) %>% 
  mutate(hours = parse_time(hours)) %>% 
  mutate(substr(hours, 1, 5)) %>% 
  select(-hours) %>% 
  rename("time" = "substr(hours, 1, 5)")

简洁实现方法

推荐以下几种简洁方案,均基于dplyr和lubridate(或hms)包:

方法1:指定格式直接解析

利用lubridate::parse_time,直接指定小时格式%H,自动补充分秒为00:00:

library(dplyr)
library(lubridate)

clean_timedata <- timedata %>%
  mutate(time = parse_time(hours, format = "%H"))

生成的time列是时间类型,如需仅显示时分,可后续用strftime(time, "%H:%M")转换为字符串,或保留时间类型方便后续时间运算。

方法2:拼接时分字符串后解析

直接将小时与:00拼接成标准时分格式,再解析:

clean_timedata <- timedata %>%
  mutate(time = parse_time(paste0(hours, ":00")))

方法3:用hms包生成轻量时间对象

如果不需要日期信息,仅需时分秒的时间对象,可使用hms包:

library(dplyr)
library(hms)

clean_timedata <- timedata %>%
  mutate(time = as_hms(paste0(hours, ":00:00")))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 14:17:48