将小时:分钟:秒(HH:MM:SS)字符串转换为正确的时间类 [英] Convert hour:minute:second (HH:MM:SS) string to proper time class

查看:52
本文介绍了将小时:分钟:秒(HH:MM:SS)字符串转换为正确的时间类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在以下数据框中,'time' 列是 character,格式为 hour:minute:second

id <- c(1, 2, 3, 4)时间 <- 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")图书馆(时间)x <- chron(时间=时间)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

In the following data frame the 'time' column is character in the format 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)

How can I convert 'time' column to a dedicated time class, so that I can perform arithmetic calculations on it?

解决方案

Use the function chron in package 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

Do some useful things, like calculating the difference between successive elements:

diff(x)
[1] 01:01:59 08:28:01 04:45:24


chron objects store the values internally as a fraction of seconds per day. Thus 1 second is equivalent to 1/(60*60*24), or 1/86400, i.e. 1.157407e-05.

So, to add times, one simple option is this:

x + 1/86400
[1] 00:00:02 01:02:01 09:30:02 14:15:26

这篇关于将小时:分钟:秒(HH:MM:SS)字符串转换为正确的时间类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆