在以下数据框中,“时间”列character
的格式为hour:minute:second
id <- c(1, 2, 3, 4)
time <- c("00:00:01", "01:02:00", "09:30:01", "14:15:25")
df <- data.frame(id, time)
如何将“时间”列转换为专用时间类,以便对其执行算术计算?
使用chron
包中的函数chron
:
time<-c("00:00:01", "01:02:00", "09:30:01", "14:15:25")
library(chron)
x <- chron(times=time)
x
[1] 00:00:01 01:02:00 09:30:01 14:15:25
做一些有用的事情,比如计算连续元素之间的差异:
diff(x)
[1] 01:01:59 08:28:01 04:45:24
chron
对象在内部将值存储为每天几分之一秒。因此 1 秒等于1/(60*60*24)
, 或1/86400
, 即1.157407e-05
。
因此,要添加时间,一个简单的选择是:
x + 1/86400
[1] 00:00:02 01:02:01 09:30:02 14:15:26
使用 base R 您可以将其转换为 class 的对象POSIXct
,但这确实为时间添加了日期:
id<-c(1,2,3,4)
time<-c("00:00:01","01:02:00","09:30:01","14:15:25")
df<-data.frame(id,time,stringsAsFactors=FALSE)
as.POSIXct(df$time,format="%H:%M:%S")
[1] "2012-08-20 00:00:01 CEST" "2012-08-20 01:02:00 CEST"
[3] "2012-08-20 09:30:01 CEST" "2012-08-20 14:15:25 CEST"
但这确实允许您对它们执行算术计算。
另一种可能的选择可能是:
time <- c("00:00:01","01:02:00","09:30:01","14:15:25")
converted.time <- as.difftime(time, units = "mins") #"difftime" class
secss <- as.numeric(converted.time, units = "secs")
hourss <- as.numeric(converted.time, units = "hours")
dayss <- as.numeric(converted.time, units="days")
甚至:
w <- strptime(x = time, format = "%H:%M:%S") #"POSIXlt" "POSIXt" class
使用包中的ITime
类data.table
:
ITime
是一个时间类,存储为一天中的整数秒数。
library(data.table)
(it <- as.ITime(time))
# [1] "00:00:01" "01:02:00" "09:30:01" "14:15:25"
it + 10
# [1] "00:00:11" "01:02:10" "09:30:11" "14:15:35"
diff(it)
# [1] "01:01:59" "08:28:01" "04:45:24"
lubridate
在时间格式上有很好的灵活性:
library(lubridate)
time_hms_1<-c("00:00:01", "01:02:00", "09:30:01", "14:15:25")
hms(time_hms_1)
#> [1] "1S" "1H 2M 0S" "9H 30M 1S" "14H 15M 25S"
time_hms_2<-c("0:00:01", "1:02:00", "9:30:01", "14:15:25")
hms(time_hms_2)
#> [1] "1S" "1H 2M 0S" "9H 30M 1S" "14H 15M 25S"
time_hm_1<-c("00:00", "01:02", "09:30", "14:15")
hm(time_hm_1)
#> [1] "0S" "1H 2M 0S" "9H 30M 0S" "14H 15M 0S"
time_hm_2<-c("0:00", "1:02", "9:30", "14:15")
hm(time_hm_2)
#> [1] "0S" "1H 2M 0S" "9H 30M 0S" "14H 15M 0S"
由reprex 包(v0.3.0)于 2020-07-03 创建
hms
使用该包的另一种选择。
id <- c(1, 2, 3, 4)
time <- c("00:00:01", "01:02:00", "09:30:01", "14:15:25")
df <- data.frame(id, time, stringsAsFactors = FALSE)
将列转换time
为类hms
# install.packages("hms")
library(hms)
df$time <- as.hms(df$time)
执行算术计算
diff(df$time)
#01:01:59
#08:28:01
#04:45:24