问题
I am trying to divide an xts object which holds a number of time series (columns; with a common date column (index). I want to divide each column by its value at a specified date (say '2010-09-30'). This is so as to re-scale the entire object with values of 1 in each column at that date (a common re-basing task). Had it been an ordinary matrix, A
, and the row I wanted to rebase to was say A[6,]
, I could just do
t(t(A)/A[6,])
and that works. But, trying to manipulate the xts object and its row subset xts['2010-09-30']
doesn't work as easily. Could someone please point me in the right direction. I realise this is very basic and I should have found the answer on my own. In fact, if there is a better method in general for rebasing time series in this manner using a package, I am happy to adopt that approach.
回答1:
xts and zoo objects are aligned by index before operations. If you want to divide an entire object by a value at a single row, you have to use coredata
(and maybe drop
) to get the value to an atomic vector (with only one element).
For example:
library(xts)
x <- xts(1:10,as.Date("2011-12-21")+1:10)
x / drop(coredata(x['2011-12-26']))
来源:https://stackoverflow.com/questions/8595053/dividing-each-row-of-an-xts-or-zoo-time-series-object-by-a-fixed-row