在R中,使用lubridate将hms对象转换为秒 [英] In R, use lubridate to convert hms objects into seconds

查看:57
本文介绍了在R中,使用lubridate将hms对象转换为秒的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

lubridate中的一个简单问题-我想将hms对象转换为自一天开始以来的适当秒数.

simple question in lubridate--I want to convert an hms object into its appropriate number of seconds since the start of the day.

例如

library(lubridate)
hms("12:34:45")

那我想确切地知道12个小时34分45秒以秒为单位

then I want to know exactly how long 12 hours, 34 minutes, and 45 seconds is, in seconds

明显的东西

seconds(hms("12:34:45"))

只是回报

45s

这不是我想要的.如何将这些hms值转换为秒?我想使用lubridate

which is not what I want. How do I convert these hms values into seconds? I'd like to use lubridate

推荐答案

使用哪个包都没关系-它将把日期/日期时间对象转换为自纪元以来的秒的POSIXct表示形式.因此,您也可以在基本R中执行此操作-因此,请在今天使用任意一天部署ISOdatetime():

It doesn't matter which package you use -- it will have convert a date / datetime object into a POSIXct representation of seconds since the epoch. So you may as well do it in base R -- so here deploy ISOdatetime() with an arbitrary day, using today:

R> difftime(ISOdatetime(2012,7,2,12,34,45), ISOdatetime(2012,7,2,0,0,0))
Time difference of 12.5792 hours

所以我们要秒:

R> difftime(ISOdatetime(2012,7,2,12,34,45), ISOdatetime(2012,7,2,0,0,0), 
+          unit="secs")
Time difference of 45285 secs

我们可以转换为数字:

R> as.numeric(difftime(ISOdatetime(2012,7,2,12,34,45), +
                       ISOdatetime(2012,7,2,0,0,0), unit="secs"))
[1] 45285

回到润滑状态,这可以说是一个错误:

And getting back to lubridate, this is arguably a bug:

> hms("12:34:45") - hms("00:00:00")
[1] 12 hours, 34 minutes and 45 seconds
R> as.numeric(hms("12:34:45") - hms("00:00:00"))
[1] 45
R>

这篇关于在R中,使用lubridate将hms对象转换为秒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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