我在 R 中有一个“时间”列,在 HH:MM:SS 中有一组字符时间值但是,有些时间没有秒数,这使得从 char 到 chron() 的转换不可能
例子:
图书馆(时间)
x <- c("08:25:18","08:25","08:24:57","08:24:47")
我想将 x 转换为 chron(),但没有秒数,它将该值转换为 N/A
如何将 :00 秒添加到需要它的人?谢谢
我在 R 中有一个“时间”列,在 HH:MM:SS 中有一组字符时间值但是,有些时间没有秒数,这使得从 char 到 chron() 的转换不可能
例子:
图书馆(时间)
x <- c("08:25:18","08:25","08:24:57","08:24:47")
我想将 x 转换为 chron(),但没有秒数,它将该值转换为 N/A
如何将 :00 秒添加到需要它的人?谢谢
我们可以转换为日期时间,format
然后应用times
library(chron)
library(lubridate)
out1 <- times(format(parse_date_time(x, c('HMS', 'HM')), "%H:%M:%S"))
str(out1)
#'times' num [1:4] 08:25:18 08:25:00 08:24:57 08:24:47
# - attr(*, "format")= chr "h:m:s"
或指定times
在chron
chron(times = format(parse_date_time(x, c('HMS', 'HM')), "%H:%M:%S"))
或使用as.ITime
from data.table
which 会起作用
library(data.table)
as.ITime(x)
#[1] "08:25:18" "08:25:00" "08:24:57" "08:24:47"