Sorting a zoo object by value

你。 提交于 2019-12-13 21:01:04

问题


I have a zoo time series object. How do I sort it by value, while preserving the dates?

If this is my series:

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

The result should be:

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

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.


回答1:


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)

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)))

Now sort 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


来源:https://stackoverflow.com/questions/21101493/sorting-a-zoo-object-by-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!