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.txt 中?我尝试了灼热的堆栈溢出,但我得到了 data.frame 而不是 xts 的解决方案。是吗,我需要首先将其转换为 df,然后命名列。
此外,xts 采用 1970-01-02 05:30:00
等日期。如何更改 xts 说 12/1/2009 12:00:00
。
最佳答案
让我们首先创建一个可重现的示例:
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
现在设置(重命名)列名并不困难,可以使用 names
、colnames
或 setNames
。
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
关于r - 在 XTS 中添加列名称并更改 XTS 中的日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53442230/