Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create an XTS object with datestamps but no columns initially

Tags:

r

xts

x is an xts object full of data; let's assume OHLC data for the sake of example. I want to create another xts object, with the same size and datestamps, but different columns (e.g. some indicators).

My current approach feels crude:

a = x$close
for(nn in 1:10){
    z = analysis(x,nn) #Returns an enhanced version of x
    z2 = z$result   #Get out just the data I want, so I can rename the column
    colnames(z2) = paste("result",nn,sep="_")
    a = cbind(a,z2) #Merge in each result
    }
a$close = NULL  #Tidyup

I.e. I bring in just one column from x, any old column, just to get the structure, then throw that away at the end. (It works, so I'm happy, but it feels like there must be a better way.)

I tried some ideas like this:

a = xts(index(x))
a = xts(orderby=index(x))
a = as.xts(index(x))
a = as.xts(orderby=index(x))

But they give me empty XTS objects. E.g. when I then try this I get an error:

a$dummy = 1
like image 284
Darren Cook Avatar asked Jul 20 '11 01:07

Darren Cook


2 Answers

Note the argument is order.by, not orderby. That doesn't solve your issue though. What you're looking for is:

a <- xts(order.by=index(x))
a <- merge(a, dummy=1)

a$dummy <- 1 doesn't work because zoo objects can be a vector or a matrix, while xts objects are always a matrix and there's no $<-.xts method.

like image 171
Joshua Ulrich Avatar answered Oct 31 '22 22:10

Joshua Ulrich


Try this:

library(xts)
L <- list()
L$x <- xts(1:4, as.Date(1:4))
L$y <- xts(1:4, as.Date(1:4))
do.call("merge", L)
like image 32
G. Grothendieck Avatar answered Oct 31 '22 23:10

G. Grothendieck