R:多元时间序列的滚动排名?

发布于 2024-10-01 18:42:25 字数 396 浏览 0 评论 0原文

我想每天对一组变量进行排名(从 zoo 系列开始)。

这是一个示例:

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

我知道执行此操作的唯一方法是使用 rollapply,但这非常慢。

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

还有其他建议吗?

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

Here's 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 to do this is with rollapply, but this is quite slow.

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

Any other suggestions?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

π浅易 2024-10-08 18:42:25

首先,感谢您发送完整且可复制的示例。

其次,我喜欢你的解决方案。您可能很难使其更快但又保持简单。一种解决方案是直接处理底层矩阵(而不是动物园对象):

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

然后重新附加时间索引。这可能会更快,但不一定更具防御性或更容易阅读。

First off, thanks for sending a complete and reproducible example.

Secondly, I like your solution. You may be hard-pressed to make it much faster yet keeping it simple. One solution is to jst work on the underlying matrix (rather than the zoo object):

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

and to then re-attach the time index. That may be faster, but not necessarily more defensive or more easily readable.

奢望 2024-10-08 18:42:25

我认为你正在以正确的方式处理这件事。使用 order 而不是 rank 会快一点,但我不明白这为什么“相当慢”。也许您可以详细说明一下您的实际问题?

> 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 

I think you're going about this the right way. Using order instead of rank is a bit faster, but I don't see how this is "quite slow". Maybe you could elaborate a bit on your actual 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 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文