【问题标题】:Get date of timeseries object获取时间序列对象的日期
【发布时间】:2014-12-27 19:42:56
【问题描述】:

我有一个单独创建的具有每日频率的时间序列对象:

my.timeseries= ts(data= 1:10, start= c(2014,1,1), frequency = 365.25)

如何从这个时间序列对象中取回日期作为 POSIXct 向量 ("2014-01-01 UTC" ...)?

【问题讨论】:

  • ts 不适合约会。建议你使用 zoo 或 xts。 library(zoo); z <- zooreg(1:10, as.Date("2014-01-01"))
  • 不幸的是 ts 对象已经存在。所以我寻找一个处理 ts 的解决方案。
  • 如果您知道 my.timeseries 包含从年初开始的连续日期,那么这会将其转换为具有 Date 类索引的 zooreg 系列:zooreg(coredata(my.timeseries), as.Date(as.yearmon(start(my.timeseries))))

标签: r date time-series


【解决方案1】:

这是一种可能的方法。我不确定是否应该这样做,但它似乎有效。

使用您现有的时间序列,尝试

p <- paste(attr(my.timeseries, "tsp")[1], my.timeseries)
as.POSIXct(as.Date(p, "%Y %j"))
#  [1] "2014-01-01 UTC" "2014-01-02 UTC" "2014-01-03 UTC"
#  [4] "2014-01-04 UTC" "2014-01-05 UTC" "2014-01-06 UTC"
#  [7] "2014-01-07 UTC" "2014-01-08 UTC" "2014-01-09 UTC"
# [10] "2014-01-10 UTC"

正如 G. Grothendieck 在 cmets 中所指出的,这里有一个更通用的解决方案

p <- paste(start(my.timeseries), seq_along(my.timeseries))
as.Date(p, "%Y %j")
# [1] "2014-01-01" "2014-01-02" "2014-01-03" "2014-01-04"
# [5] "2014-01-05" "2014-01-06" "2014-01-07" "2014-01-08"
# [9] "2014-01-09" "2014-01-10"

as.Date 可能会更好地避免任何时区问题。

【讨论】:

    【解决方案2】:

    我强烈建议您使用 xts 对象而不是 ts。

    这是一个复制你想要的代码:

    library(xts)
    my.index = seq(from = as.Date("2014-01-01"), by = "day", length.out = 10)
    my.timeseries = xts(x = 1:10, order.by = my.index)
    index(my.timeseries)
    

    如果有帮助,请告诉我们:)

    罗曼

    【讨论】:

    • 谢谢。不幸的是 ts 对象已经存在。所以我寻找一个处理 ts 的解决方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-25
    • 2019-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多