R:多元时间序列的滚动排名?
我想每天对一组变量进行排名(从 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先,感谢您发送完整且可复制的示例。
其次,我喜欢你的解决方案。您可能很难使其更快但又保持简单。一种解决方案是直接处理底层矩阵(而不是动物园对象):
然后重新附加时间索引。这可能会更快,但不一定更具防御性或更容易阅读。
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):
and to then re-attach the time index. That may be faster, but not necessarily more defensive or more easily readable.
我认为你正在以正确的方式处理这件事。使用
order
而不是rank
会快一点,但我不明白这为什么“相当慢”。也许您可以详细说明一下您的实际问题?I think you're going about this the right way. Using
order
instead ofrank
is a bit faster, but I don't see how this is "quite slow". Maybe you could elaborate a bit on your actual problem?