按列名从 xts 中选择

Selecting from xts by column name

我试图在函数中按名称对 xts 对象中的特定列进行操作,但我一直收到错误消息:

Error in if (length(c(year, month, day, hour, min, sec)) == 6 && all(c(year, : missing value where TRUE/FALSE needed In addition: Warning messages: 1: In as_numeric(YYYY) : NAs introduced by coercion 2: In as_numeric(YYYY) : NAs introduced by coercion

如果我有一个 xts 对象:

xts1 <- xts(x=1:10, order.by=Sys.Date()-1:10)
xts2 <- xts(x=1:10, order.by=Sys.Date()+1:10)
xts3 <- merge(xts1, xts2)

然后我可以 select 一个特定的列:

xts3$xts1

使用数据框,我可以将 xts3 传递给另一个函数,然后 select 一个特定的列:

xts3['xts1']

但是如果我尝试对 xts 对象做同样的事情,我会得到上面的错误。例如

testfun <- function(xts_data){
  print(xts_data['xts1'])
}

调用方式:

testfun(xts3)

这个有效:

testfun <- function(xts_data){
  print(xts_data[,1])
}

但我真的很想 select 按名称,因为我不能确定列的顺序。

任何人都可以建议如何解决这个问题吗?

谢谢!

键入 ?`[.xts`,您会看到该函数有一个 i 和一个 j 参数(以及其他参数)。

i - the rows to extract. Numeric, timeBased or ISO-8601 style (see details)

j - the columns to extract, numeric or by name

您将 'xts1' 作为 i 参数传递,而它应该是 j。所以你的函数应该是

testfun <- function(xts_data){
  print(xts_data[, 'xts1']) # or xts3[j = 'xts1']
}

xts-对象有classc("xts", "zoo"),这意味着它们是具有特殊属性的矩阵,由它们的创建函数分配。尽管 $ 不会成功处理矩阵,但由于 $.zoo 方法,它可以处理 xtszoo 对象。 (也不建议在函数内部使用 $,因为名称评估混淆和部分名称匹配的可能性。)参见:?xts 并检查使用第一个创建的 sample.xts 对象例如 str:

> ?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" 元素,然后 returns 由 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" 元素,但是 you/we 还需要读取 ?rbind.xts。)