在 R 中处理时间戳 [英] Dealing with timestamps in R

查看:53
本文介绍了在 R 中处理时间戳的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有多个测量值列表.在每个列表中,时间戳都被格式化为一个字符串(2009-12-24 21:00:07.0"),我知道列表中的每个测量都间隔 5 秒.我想在 R 中将所有数据组合成一个巨大的 data.frame.之后我希望能够轻松访问两次测量的时间差,所以我可能应该将数据转换为不同于字符的东西.

I have multiple lists of measurements. In each list have the timestramp formated as a string ("2009-12-24 21:00:07.0") and I know that each measurement in the list is separated by 5 seconds. I want to combine all data into a huge data.frame in R. Afterwards I want to be able to easily access the time difference of two measurements so I probably should convert data into something different than characters.

我应该使用哪种格式来存储时间?我应该使用某些包中的某些时间格式吗?

Which format should I use to store the times? Is there some time format in some package that I should use?

推荐答案

您想要来自基本 R 的(标准)POSIXt 类型,它可以以紧凑形式"作为 POSIXct (本质上是一个 double 表示自纪元以来的小数秒)或 POSIXlt 中的长格式(包含子元素).很酷的事情是在此定义了算术等 - 请参阅 help(DateTimeClasses)

You want the (standard) POSIXt type from base R that can be had in 'compact form' as a POSIXct (which is essentially a double representing fractional seconds since the epoch) or as long form in POSIXlt (which contains sub-elements). The cool thing is that arithmetic etc are defined on this -- see help(DateTimeClasses)

快速示例:

R> now <- Sys.time()
R> now
[1] "2009-12-25 18:39:11 CST"
R> as.numeric(now)
[1] 1.262e+09
R> now + 10  # adds 10 seconds
[1] "2009-12-25 18:39:21 CST"
R> as.POSIXlt(now)
[1] "2009-12-25 18:39:11 CST"
R> str(as.POSIXlt(now))
 POSIXlt[1:9], format: "2009-12-25 18:39:11"
R> unclass(as.POSIXlt(now))
$sec
[1] 11.79

$min
[1] 39

$hour
[1] 18

$mday
[1] 25

$mon
[1] 11

$year
[1] 109

$wday
[1] 5

$yday
[1] 358

$isdst
[1] 0

attr(,"tzone")
[1] "America/Chicago" "CST"             "CDT"            
R> 

至于读入,见help(strptime)

至于区别,也很简单:

R> Jan1 <- strptime("2009-01-01 00:00:00", "%Y-%m-%d %H:%M:%S")
R> difftime(now, Jan1, unit="week")
Time difference of 51.25 weeks
R> 

最后,zoo 包 是一个用途广泛且文档齐全的容器用于具有相关日期/时间索引的矩阵.

Lastly, the zoo package is an extremely versatile and well-documented container for matrix with associated date/time indices.

这篇关于在 R 中处理时间戳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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