tags:

views:

72

answers:

1

I have three vectors in an xts R object. Call them V1, V2, V3. After merging, the order of them left to right is V2, V3, V1. How do I re-arrange them so they read (from left to right) as V1, V2, V3?

+3  A: 

You can just reference the columns and re-assign them:

 x <- x[,c(2,3,1)]

Here's a working example:

> data(sample_matrix)
> x <- head(as.xts(sample_matrix, descr='my new xts object'))[,c(1,2,3)]
> x
               Open     High      Low
2007-01-02 50.03978 50.11778 49.95041
2007-01-03 50.23050 50.42188 50.23050
2007-01-04 50.42096 50.42096 50.26414
2007-01-05 50.37347 50.37347 50.22103
2007-01-06 50.24433 50.24433 50.11121
2007-01-07 50.13211 50.21561 49.99185
> x <- x[,c(2,3,1)]
> x
               High      Low     Open
2007-01-02 50.11778 49.95041 50.03978
2007-01-03 50.42188 50.23050 50.23050
2007-01-04 50.42096 50.26414 50.42096
2007-01-05 50.37347 50.22103 50.37347
2007-01-06 50.24433 50.11121 50.24433
2007-01-07 50.21561 49.99185 50.13211
Shane
Thanks very much. I will keep this notation in mind for the future. I did a less elegant work-around. My final data frame was the result of three merged vectors, so I just re-arranged the order in which I merged them.Original: merge (V2, V1, V2)Work Around: merge (V1, V2, V3)
Milktrader