简体   繁体   English

如何将以下原始数据转换为Zoo或XTS时间戳?

[英]How do I convert following raw data to zoo or xts timestamp?

My raw data in a CSV-file looks like this, ie the date-time format is %Y%m%d, the letter "T", followed by %H%M%S: 我在CSV文件中的原始数据如下所示,即日期时间格式为%Y%m%d,字母“ T”,后跟%H%M%S:

20151230T090029, 33.04
20151230T090029, 33.06
20151230T090029, 33.07
20151230T090029, 33.05
20151230T090029, 33.04
20151230T090029, 33.05
20151230T090029, 33.04

How can I make this first column a time-index in zoo or xts? 如何使第一列成为Zoo或XTS中的时间索引?

Given your data as d : 给定您的数据为d

> d
               V1    V2
1 20151230T090029 33.04
2 20151230T090029 33.06
3 20151230T090029 33.07
4 20151230T090029 33.05
5 20151230T090029 33.04
6 20151230T090029 33.05
7 20151230T090029 33.04

Then conversion to POSIX time classes can be done using the format string given in comments: 然后可以使用注释中给出的格式字符串转换为POSIX时间类:

> as.POSIXct(d$V1,format="%Y%m%dT%H%M%S")
[1] "2015-12-30 09:00:29 GMT" "2015-12-30 09:00:29 GMT"
[3] "2015-12-30 09:00:29 GMT" "2015-12-30 09:00:29 GMT"
[5] "2015-12-30 09:00:29 GMT" "2015-12-30 09:00:29 GMT"
[7] "2015-12-30 09:00:29 GMT"

And a zoo object constructed: 并构造了一个zoo对象:

> zoo(d$V2, as.POSIXct(d$V1,format="%Y%m%dT%H%M%S"))
2015-12-30 09:00:29 2015-12-30 09:00:29 2015-12-30 09:00:29 2015-12-30 09:00:29 
              33.04               33.06               33.07               33.05 
2015-12-30 09:00:29 2015-12-30 09:00:29 2015-12-30 09:00:29 
              33.04               33.05               33.04 
Warning message:
In zoo(d$V2, as.POSIXct(d$V1, format = "%Y%m%dT%H%M%S")) :
  some methods for “zoo” objects do not work if the index entries in ‘order.by’ are not unique

with that warning because all the time points are the same. 发出警告,因为所有时间点都相同。

As Josh O'Brien suggested , you can do this with read.zoo : 正如Josh O'Brien建议的那样 ,您可以使用read.zoo做到这read.zoo

library(zoo)
Lines <- "20151230T090029, 33.04
20151230T090029, 33.06
20151230T090029, 33.07
20151230T090029, 33.05
20151230T090029, 33.04
20151230T090029, 33.05
20151230T090029, 33.04"
z <- read.zoo(text=Lines, sep=",", FUN=as.POSIXct, format="%Y%m%dT%H%M%S")

Then you could deal with the identical timestamp issue Gabor mentioned by converting to xts and using xts::make.index.unique . 然后,您可以通过转换为xts并使用xts::make.index.unique来处理Gabor提到的相同时间戳问题。

library(xts)
x <- as.xts(z)
options(digits.secs=3)
(u <- make.index.unique(x, 0.001))
#                          [,1]
# 2015-12-30 09:00:29.000 33.04
# 2015-12-30 09:00:29.000 33.06
# 2015-12-30 09:00:29.001 33.07
# 2015-12-30 09:00:29.002 33.05
# 2015-12-30 09:00:29.003 33.04
# 2015-12-30 09:00:29.004 33.05
# 2015-12-30 09:00:29.005 33.04

See How R formats POSIXct with fractional seconds for why the fractional seconds print in a way that makes them look incorrect. 请参阅R如何用小数秒格式化POSIXct,以了解为什么小数秒以一种使它们看起来不正确的方式打印。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM