Reputation: 53
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.
Upvotes: 1
Views: 2698
Reputation: 174938
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
Upvotes: 6