乘以 xts 对象与向量化 xts 对象时的不同结果

Different result when multiplying xts objects vs. vector'ed xts objects

我有以下原码

prices <- c(11.44, 12.64, 13.12, 11.98, 19.34)
dates <- seq(as.Date("2011-07-01"), by=1, len=length(prices))
ts.prices <- xts(prices, order.by =dates)

covariance <- function(x, convert.to.vec=FALSE) {
  if (convert.to.vec == TRUE)
    x <- as.vector(x)

  xbar <- mean(x)
  N <- length(x)
  i <- 1
  covariance <- sum((x[1:(N-i)]-xbar)*(x[(1+i):N]-xbar))

  return(covariance)
}

无论convert.to.vecTRUE还是FALSEcovariance函数的输出都会不同:

> covariance(ts.prices, TRUE)
[1] -5.679376
> covariance(ts.prices, FALSE)
[1] 4.445328

添加一些变量和 prints 以使代码调试更容易之后:

covariance <- function(x, convert.to.vec=FALSE) {
  if (convert.to.vec == TRUE)
    x <- as.vector(x)
  xbar <- mean(x)
  N <- length(x)
  i <- 1

  term.1 <- x[1:(N-i)]-xbar
  term.2 <- x[(1+i):N]-xbar
  term.3 <- term.1*term.2
  covariance <- sum(term.3)
  print(term.1)
  print(term.2)
  print(term.3)
  print(covariance)
  #covariance <- sum((x[1:(N-i)]-xbar)*(x[(1+i):N]-xbar))
  #return(covariance)
 }

我们可以看到 term.3 的值是不同的:

> covariance(ts.prices, TRUE)
[1] -2.264 -1.064 -0.584 -1.724
[1] -1.064 -0.584 -1.724  5.636
[1]  2.408896  0.621376  1.006816 -9.716464
[1] -5.679376
> covariance(ts.prices, FALSE)
             [,1]
2011-07-01 -2.264
2011-07-02 -1.064
2011-07-03 -0.584
2011-07-04 -1.724
             [,1]
2011-07-02 -1.064
2011-07-03 -0.584
2011-07-04 -1.724
2011-07-05  5.636
                 e1
2011-07-02 1.132096
2011-07-03 0.341056
2011-07-04 2.972176
[1] 4.445328

convert.to.vecTRUE时,term.3包含4个浮点数,而当convert.to.vecFALSE时,term.3包含3个浮点数。所以我假设不同的值是由两个 xts 对象与两个向量化 xts 对象相乘引起的。为什么会这样?

DC

根据@alexis_laz的评论,当 Ops.xts 函数如 +* 用于两个 xts 对象时,两者如果对象的索引不相同,则对象首先相互合并,正如我们在 xts`s sourcecode:

中看到的那样
if( NROW(e1)==NROW(e2) && identical(.index(e1),.index(e2)) ) {
  .Class <- "matrix"
  NextMethod(.Generic)
} else {
  tmp.e1 <- merge.xts(e1, e2, all=FALSE, retclass=FALSE, retside=c(TRUE,FALSE))
  e2 <- merge.xts(e2, e1, all=FALSE, retclass=FALSE, retside=c(TRUE,FALSE))
  e1 <- tmp.e1
  .Class <- "matrix"
  NextMethod(.Generic)
}

在我的示例中,term.1term.2 没有相同的索引,因此两个对象被合并,Ops 函数 * returns 一个仅包含重叠日期的对象。一种解决方案是在原始 x 对象上调用 coredata