【问题标题】:How do I convert following raw data to zoo or xts timestamp?如何将以下原始数据转换为 zoo 或 xts 时间戳?
【发布时间】:2016-04-08 11:28:42
【问题描述】:

我在 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

如何使第一列成为 zoo 或 xts 中的时间索引?

【问题讨论】:

  • 逗号后面是什么?
  • 也许使用read.zoo(),将其format= 参数设置为format="%Y%m%dT%H%M%S"
  • 请注意,zoo 不支持具有多个相同索引的系列。
  • @Nancy,这是有代价的。
  • @JoshO'Brien 我尝试了你的建议,但是 T 之后的所有内容都消失了,所以我只剩下日期了..

标签: r xts zoo


【解决方案1】:

假设您的数据为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

然后可以使用 cmets 中给出的格式字符串转换为 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"

并构造了一个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

带有该警告,因为所有时间点都相同。

【讨论】:

    【解决方案2】:

    作为Josh O'Brien suggested,您可以使用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")
    

    然后您可以通过转换为 xts 并使用 xts::make.index.unique 来处理相同的时间戳问题 Gabor mentioned

    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
    

    请参阅How R formats POSIXct with fractional seconds,了解为什么小数秒的打印方式使它们看起来不正确。

    【讨论】:

      猜你喜欢
      • 2011-05-21
      • 1970-01-01
      • 2019-08-13
      • 2013-12-09
      • 1970-01-01
      • 2019-04-03
      • 2020-06-03
      • 2021-10-31
      • 2021-11-12
      相关资源
      最近更新 更多