开发者

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开发者_StackOverflow社区 values.

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.

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. For ordinary matrices the default is 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. To get the same behaviour in both cases you could use 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:

> 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 ...
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜