[英]R idiom for %*% using xts
I am working with some code that uses the %*%
operator to apply vectors of weights to vectors representing time series. 我正在使用一些使用
%*%
运算符的代码将权重向量应用于表示时间序列的向量。 I would like to use xts for the time series, but the %*%
operator is not understanding that it should ignore the xts index values. 我想使用xts作为时间序列,但
%*%
运算符不理解它应该忽略xts索引值。
I know I can use coredata()
to pull out my series values as a vector, operate on the values, and merge them back in, but I was wondering whether there was a good native xts function I should be using. 我知道我可以使用
coredata()
将我的系列值作为向量拉出,对值进行操作,并将它们合并回来,但我想知道是否有一个好的本机xts函数我应该使用。
EDIT: code sample illustrating the difference I'm seeing in behavior. 编辑:代码示例说明我在行为中看到的差异。
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
If you check help("[.xts")
you'll notice that drop
defaults to FALSE
. 如果你检查
help("[.xts")
你会发现drop
默认为FALSE
。 For ordinary matrices the default is TRUE
. 对于普通矩阵,默认值为
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 ...
That means that your xx
is a 180 element vector whereas your yy
is a 180 x 1 matrix. 这意味着你的
xx
是180元素向量,而你的yy
是180 x 1矩阵。 To get the same behaviour in both cases you could use yy <- o_xts[1:len, drop=TRUE]
. 要在两种情况下获得相同的行为,您可以使用
yy <- o_xts[1:len, drop=TRUE]
。
I have not (yet) seen any evidence to support the premise of the question, and when I do my own simple test on the first example in help(xts) I come up with contrary evidence: 我还没有看到任何证据支持这个问题的前提,当我在帮助(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 ...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.