【问题标题】:Adding column names in XTS and changing dates in XTS在 XTS 中添加列名并在 XTS 中更改日期
【发布时间】:2019-04-25 19:16:21
【问题描述】:

xts 看起来像:

An ‘xts’ object on 1970-01-02 05:30:00/1976-03-29 05:30:00 containing:
  Data: num [1:2279, 1] 0.295 0.316 0.315 0.301 0.292 ...
 - attr(*, "dimnames")=List of 2
  ..$ : NULL
  ..$ : NULL
  Indexed by objects of class: [POSIXct,POSIXt] TZ: 
  Original class: 'double'  
  xts Attributes: NULL

此 XTS 是通过其他代码生成的,没有如

所示的列名
dimnames(cor_BG_xts)
[[1]]
NULL
[[2]]
NULL
colnames(cor_BG_xts)
NULL

如何将列名添加到 xts.我尝试了灼热的堆栈溢出,但我得到了 data.frame 而不是 xts 的解决方案。做,我需要先将其转换为 df 然后命名列。 此外,xts 采用1970-01-02 05:30:00 之类的日期。如何更改 xts 说 12/1/2009 12:00:00

【问题讨论】:

    标签: r time-series xts


    【解决方案1】:

    让我们首先创建一个可重现的示例:

    library(xts)
    
    dates <- seq.Date(as.Date("2018-11-19"), as.Date("2018-11-23"), by = "day")
    numbers <- 1:5
    
    my_xts <- xts(numbers, dates)
    my_xts
                        [,1]
    2018-11-19 05:30:00    1
    2018-11-20 05:30:00    2
    2018-11-21 05:30:00    3
    2018-11-22 05:30:00    4
    2018-11-23 05:30:00    5
    

    现在设置(重命名)列名并不困难,可以使用namescolnamessetNames

    names(my_xts) <- "new_column_name"
    # setNames / colnames works as well.
    # my_xts <- setNames(my_xts, "new_column_name")
    # colnames(my_xts) <- "new_column_name"
    # 
    my_xts
                        new_column_name
    2018-11-19 05:30:00               1
    2018-11-20 05:30:00               2
    2018-11-21 05:30:00               3
    2018-11-22 05:30:00               4
    2018-11-23 05:30:00               5
    

    更改索引格式,使用indexFormat。您可以使用?strptime 的详细信息中提到的任何日期时间格式。

    indexFormat(my_xts) <- "%d/%m/%Y %H:%M:%S"
    my_xts
                        new_column_name
    19/11/2018 05:30:00               1
    20/11/2018 05:30:00               2
    21/11/2018 05:30:00               3
    22/11/2018 05:30:00               4
    23/11/2018 05:30:00               5
    

    【讨论】:

    • 非常感谢您的回答。我的问题是时间序列本身正在创建时间戳(从 1970 年开始的索引)。现在我明白这是因为我应该将 xts 传递给生成这个 xts 对象的函数。在将 xts 传递给函数时,它需要所需的时间戳。非常感谢关于重命名 xts 列的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-28
    • 2020-08-19
    • 2020-08-07
    • 2018-06-08
    • 2015-02-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多