xts-objects 具有类c("xts", "zoo"),这意味着它们是具有特殊属性的矩阵,这些属性由它们的创建函数分配。尽管$ 不会成功处理矩阵,但由于$.zoo 方法,它可以处理xts 和zoo 对象。 (也不建议在函数内部使用$,因为可能会造成名称评估混淆和部分名称匹配。)请参阅:?xts 并检查使用str 的第一个示例创建的sample.xts 对象:
> ?xts
starting httpd help server ... done
> data(sample_matrix)
> sample.xts <- as.xts(sample_matrix, descr='my new xts object')
>
> str(sample.xts)
An ‘xts’ object on 2007-01-02/2007-06-30 containing:
Data: num [1:180, 1:4] 50 50.2 50.4 50.4 50.2 ...
- attr(*, "dimnames")=List of 2
..$ : NULL
..$ : chr [1:4] "Open" "High" "Low" "Close"
Indexed by objects of class: [POSIXct,POSIXt] TZ:
xts Attributes:
List of 1
$ descr: chr "my new xts object"
class(sample.xts)
# [1] "xts" "zoo"
这解释了为什么建议使用 xts3[ , "x"] 或等效的 xts3[ , 1] 的早期答案应该成功。 [.xts 函数首先提取“Data”元素,然后返回由j-参数指定的命名或编号列。
str(xts3)
An ‘xts’ object on 2018-05-24/2018-06-13 containing:
Data: int [1:20, 1:2] 10 9 8 7 6 5 4 3 2 1 ...
- attr(*, "dimnames")=List of 2
..$ : NULL
..$ : chr [1:2] "xts1" "xts2"
Indexed by objects of class: [Date] TZ: UTC
xts Attributes:
NULL
> xts3[ , "xts1"]
xts1
2018-05-24 10
2018-05-25 9
2018-05-26 8
2018-05-27 7
2018-05-28 6
2018-05-29 5
2018-05-30 4
2018-05-31 3
2018-06-01 2
2018-06-02 1
2018-06-04 NA
2018-06-05 NA
2018-06-06 NA
2018-06-07 NA
2018-06-08 NA
2018-06-09 NA
2018-06-10 NA
2018-06-11 NA
2018-06-12 NA
2018-06-13 NA
merge.xts 操作可能未达到您的预期,因为日期范围没有重叠。您可能想要:
> xts4 <- rbind(xts1, xts2)
> str(xts4)
An ‘xts’ object on 2018-05-24/2018-06-13 containing:
Data: int [1:20, 1] 10 9 8 7 6 5 4 3 2 1 ...
Indexed by objects of class: [Date] TZ: UTC
xts Attributes:
NULL
请注意,rbind.xts-操作未能交付具有共享列名的对象,因此需要数字访问。 (我希望有一个名为“Data”的元素,但你/我们还需要阅读 ?rbind.xts。)