Skip to content

column transposition with xts

5 messages · Aleks Clark, Joshua Ulrich, Gabor Grothendieck +1 more

#
Aleks,

This isn't the most elegant solution, especially with large data sets,
but it is *a* solution.  The code below yields a 24-column xts object
(20 lags of close prices, plus the original OHLC series).

library(xts)
library(quantmod)

data(sample_matrix)
x <- as.xts(sample_matrix[1:50,])

res <- x
for(i in 1:20) { res <- cbind(res,lag(Cl(x),i)) }

HTH,
Josh
--
http://www.fosstrading.com
On Mon, Sep 14, 2009 at 5:53 AM, Aleks Clark <aleks.clark at gmail.com> wrote:
1 day later
#
Josh,

was hoping to avoid a for loop, but I guess this is as good as it gets
:) luckily I should only have to run this once.

thanks,

Aleks
On Mon, Sep 14, 2009 at 9:52 PM, Joshua Ulrich <josh.m.ulrich at gmail.com> wrote:
--
Aleks Clark
#
zoo's lag function supports vector lags so try this
where x is your xts object:

z <- as.zoo(Cl(x))
zz <- lag(z, -seq(0, 20))

zz is a zoo object and you can use as.xts(zz) to convert it back to
xts if needed.

Note that lag.zoo follows the R convention of having negative lag mean
move the lagged series forward in time where lag.xts uses the opposite
convention.
On Mon, Sep 14, 2009 at 6:53 AM, Aleks Clark <aleks.clark at gmail.com> wrote:
#
This probably won't be much better, but it is cleaner code:

*note: Lag is in quantmod*
Lag.1    Lag.2    Lag.3    Lag.4    Lag.5    Lag.6    Lag.7
2007-02-15 51.04699 50.90106 50.96653 50.91160 50.69562 50.67686 50.81383
2007-02-16 51.05185 51.04699 50.90106 50.96653 50.91160 50.69562 50.67686
2007-02-17 51.02164 51.05185 51.04699 50.90106 50.96653 50.91160 50.69562
2007-02-18 51.13653 51.02164 51.05185 51.04699 50.90106 50.96653 50.91160
2007-02-19 51.15151 51.13653 51.02164 51.05185 51.04699 50.90106 50.96653
2007-02-20 51.17899 51.15151 51.13653 51.02164 51.05185 51.04699 50.90106
              Lag.8    Lag.9   Lag.10   Lag.11   Lag.12   Lag.13   Lag.14
2007-02-15 50.60611 50.49865 50.69783 50.55509 50.43109 50.36928 50.35784
2007-02-16 50.81383 50.60611 50.49865 50.69783 50.55509 50.43109 50.36928
2007-02-17 50.67686 50.81383 50.60611 50.49865 50.69783 50.55509 50.43109
2007-02-18 50.69562 50.67686 50.81383 50.60611 50.49865 50.69783 50.55509
2007-02-19 50.91160 50.69562 50.67686 50.81383 50.60611 50.49865 50.69783
2007-02-20 50.96653 50.91160 50.69562 50.67686 50.81383 50.60611 50.49865
             Lag.15   Lag.16   Lag.17   Lag.18   Lag.19   Lag.20
2007-02-15 50.22578 50.02180 49.91875 49.88096 50.01091 50.07024
2007-02-16 50.35784 50.22578 50.02180 49.91875 49.88096 50.01091
2007-02-17 50.36928 50.35784 50.22578 50.02180 49.91875 49.88096
2007-02-18 50.43109 50.36928 50.35784 50.22578 50.02180 49.91875
2007-02-19 50.55509 50.43109 50.36928 50.35784 50.22578 50.02180
2007-02-20 50.69783 50.55509 50.43109 50.36928 50.35784 50.22578

HTH
Jeff
On Wed, Sep 16, 2009 at 5:56 AM, Aleks Clark <aleks.clark at gmail.com> wrote: