在以下数据框中,“时间”列为character
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)
我想知道如何将其转换为time
,以便我可以对其进行算术计算。
答案 0 :(得分:35)
使用包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
答案 1 :(得分:16)
使用base R你可以将它转换为类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"
但这确实允许你对它们进行算术运算。
答案 2 :(得分:2)
另一种可能的替代方案可能是:
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
答案 3 :(得分:2)
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 package(v0.3.0)于2020-07-03创建
答案 4 :(得分:0)
还可以使用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
答案 5 :(得分:0)
使用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"