1

我正在使用一些代码,这些代码使用%*%运算符将​​权重向量应用于表示时间序列的向量。我想将 xts 用于时间序列,但%*%操作员不理解它应该忽略 xts 索引值。

我知道我可以使用coredata()将我的系列值作为向量提取出来,对这些值进行操作,然后将它们合并回来,但我想知道是否应该使用一个好的原生 xts 函数。

编辑:代码示例说明了我在行为中看到的差异。

library(xts)
data(sample_matrix)
s<-as.xts(sample_matrix)

o_xts<-s$Open
c_xts<-coredata(s$Open)

len <-length(c_xts)
len2<-len/2
xx<-c_xts[1:len]
outp<-0*0:len2
outp[2] <- xx%*%exp((1:(2*len2))*1.i*pi/len2)
#completes without issue

len <-length(o_xts)
len2<-len/2
yy<-o_xts[1:len]
outp<-0*0:len2
outp[2] <- yy%*%exp((1:(2*len2))*1.i*pi/len2)
Warning message:
In outp[2] <- yy %*% exp((1:(2 * len2)) * (0+1i) * pi/len2) :
  number of items to replace is not a multiple of replacement length
4

2 回答 2

3

如果您检查help("[.xts"),您会注意到drop默认为FALSE. 对于普通矩阵,默认值为TRUE.

str(o_xts[1:len])
# An ‘xts’ object from 2007-01-02 to 2007-06-30 containing:
#   Data: num [1:180, 1] 50 50.2 50.4 50.4 50.2 ...
#  - attr(*, "dimnames")=List of 2
#   ..$ : NULL
#   ..$ : chr "Open"
#   Indexed by objects of class: [POSIXct,POSIXt] TZ: 
#   xts Attributes:  
#  NULL

str(c_xts[1:len])
# num [1:180] 50 50.2 50.4 50.4 50.2 ...

这意味着您xx是一个 180 元素向量,而您yy是一个 180 x 1 矩阵。要在这两种情况下获得相同的行为,您可以使用yy <- o_xts[1:len, drop=TRUE].

于 2011-10-12T10:13:26.823 回答
1

我(还)没有看到任何支持问题前提的证据,当我对 help(xts) 中的第一个示例进行自己的简单测试时,我提出了相反的证据:

> data(sample_matrix)
> sample.xts <- as.xts(sample_matrix, descr='my new xts object')
> str(coredata(sample.xts))
 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"
> str(coredata(sample.xts) %*% c(3, 3,3,3) )
 num [1:180, 1] 601 604 604 604 602 ...
> str(sample.xts %*% c(3, 3,3,3) )
 num [1:180, 1] 601 604 604 604 602 ...
于 2011-09-24T00:23:43.967 回答