在R中将字符转换为时间

Ali*_*vil 26 r

在以下数据框中,"时间"列为 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)
Run Code Online (Sandbox Code Playgroud)

我想知道如何将其转换为time可以对其进行算术运算.

And*_*rie 37

使用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
Run Code Online (Sandbox Code Playgroud)

做一些有用的事情,比如计算连续元素之间的差异:

diff(x)
[1] 01:01:59 08:28:01 04:45:24
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)


Sac*_*amp 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"
Run Code Online (Sandbox Code Playgroud)

但这确实允许您对它们执行算术计算.


Hen*_*rik 7

使用包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"
Run Code Online (Sandbox Code Playgroud)


Wal*_*ldi 7

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"
Run Code Online (Sandbox Code Playgroud)

由reprex 包(v0.3.0)于 2020-07-03 创建


Fáb*_*bio 6

另一种可能的选择是:

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")
Run Code Online (Sandbox Code Playgroud)

甚至:

w <- strptime(x = time, format = "%H:%M:%S") #"POSIXlt" "POSIXt" class
Run Code Online (Sandbox Code Playgroud)