R: Rank rolling multidimensional time series?

I want to rank a set of variables every day (starting with the zoo series).

Here is an example:

 set.seed(1) x <- zoo(matrix(rnorm(9), nrow=3), as.Date("2010-01-01") + 0:2) colnames(x) <- letters[1:3] 

The only way I know this is rollapply , but it's pretty slow.

 > rollapply(x, 1, rank, by.column=FALSE) abc 2010-01-01 1 3 2 2010-01-02 1 2 3 2010-01-03 1 2 3 

Any other suggestions?

+4
source share
2 answers

First of all, thanks for submitting a complete and reproducible example.

Secondly, I like your decision. It may be difficult for you to make it much faster, but at the same time it is simple. One solution is to work jst on the base matrix (and not the zoo object):

 > X <- coredata(x) > t(apply(X, 1, rank)) abc [1,] 1 3 2 [2,] 1 2 3 [3,] 1 2 3 > 

and then reattach the time index. It can be faster, but not necessarily more protective or easier to read.

+2
source

I think you will get better. Using order instead of rank bit faster, but I don't see how it is β€œpretty slow”. Maybe you can tell a little about your real problem?

 > system.time(for(i in 1:1000) rollapply(z, 1, order, by.column=FALSE)) user system elapsed 1 0 1 > system.time(for(i in 1:1000) rollapply(z, 1, rank, by.column=FALSE)) user system elapsed 1.34 0.00 1.34 
+2
source

All Articles