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.
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 thatdropdefaults toFALSE. For ordinary matrices the default isTRUE.That means that your
xxis a 180 element vector whereas youryyis a 180 x 1 matrix. To get the same behaviour in both cases you could useyy <- o_xts[1:len, drop=TRUE].