首页 > 解决方案 > 选择要在 R 中操作的 xts 列

问题描述

我有以下标题:

"Index","Open","High","Low","Close","Volume"

我只想在名为价格的表中使用收盘量,我如何只选择收盘列所以我只能使用该数据?

我尝试了一些类似的东西

closePrices <- prices("Close") 

closePrices <- prices[Close]

两者都抛出错误

标签: rxts

解决方案


有几个选项可以做到这一点。请参阅下面的示例。

library(xts)
library(quantmod)

data(sample_matrix)
sample_xts <- as.xts(sample_matrix)

基于列名

xts_close <- sample_xts[, "Close"]

head(xts_close)
              Close
2007-01-02 50.11778
2007-01-03 50.39767
2007-01-04 50.33236
2007-01-05 50.33459
2007-01-06 50.18112
2007-01-07 49.99185

或者

xts_close <- sample_xts$Close

head(xts_close)
              Close
2007-01-02 50.11778
2007-01-03 50.39767
2007-01-04 50.33236
2007-01-05 50.33459
2007-01-06 50.18112
2007-01-07 49.99185

使用 quantmod

# using quantmod::Cl
quant_close <- Cl(sample_xts)

head(quant_close)
              Close
2007-01-02 50.11778
2007-01-03 50.39767
2007-01-04 50.33236
2007-01-05 50.33459
2007-01-06 50.18112
2007-01-07 49.99185

all.equal(xts_close, quant_close)

[1] TRUE

推荐阅读