按值对动物园对象排序 [英] Sorting a zoo object by value
问题描述
我有一个动物园时间序列对象.如何在保留日期的同时按值对它进行排序?
I have a zoo time series object. How do I sort it by value, while preserving the dates?
如果这是我的系列作品
2013-10-02 2013-10-03 2013-10-04 2013-10-07 2013-10-08 2013-10-09
-0.02 0.00 0.00 0.04 0.00 0.02
结果应为:
2013-10-02 2013-10-03 2013-10-04 2013-10-08 2013-10-09 2013-10-07
-0.02 0 0 0 0.02 0.04
普通sort
按日期(非值)对Zoo对象进行排序.动物园对象(日期,1个值系列)的值是NULL,因此无法指定我要按第二列排序.
Ordinary sort
sorts the zoo object by date (not value). zoo object (date, 1 value series) has dim NULL, so it's not possible to specify that I want to sort by the second column.
推荐答案
在数据框中使用数据并将其转换为"zoo"
对象:
Using your data in a data frame and converting to a "zoo"
object:
df <- data.frame(Dates = as.Date(c("2013-10-02", "2013-10-03", "2013-10-04",
"2013-10-07", "2013-10-08", "2013-10-09")),
Values = c(-0.02, 0.00, 0.00, 0.04, 0.00, 0.02))
library("zoo")
zdf <- zoo(df$Values, df$Dates)
虽然@Joshua是正确的,但是您始终可以转换回数据框表示形式并进行排序,而您只需要处理整个过程中的日期保留即可.例如:
Whilst @Joshua is correct, you can always convert back to a data frame representation and sort that, you just have to handle the preservation of the dates through the process. For example:
df2 <- as.data.frame(zdf)
df2 <- transform(df2, Dates = as.Date(rownames(df2)))
现在排序df2
df2[order(df2$zdf), ]
R> df2[order(df2$zdf), ]
zdf Dates
2013-10-02 -0.02 2013-10-02
2013-10-03 0.00 2013-10-03
2013-10-04 0.00 2013-10-04
2013-10-08 0.00 2013-10-08
2013-10-09 0.02 2013-10-09
2013-10-07 0.04 2013-10-07
这篇关于按值对动物园对象排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!