按年和月对年-月列进行排序 [英] Sort year-month column by year AND month

查看:85
本文介绍了按年和月对年-月列进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试订购已存储在数据框中的一系列时间数据.格式为:

I am trying to order a series of time data I have stored in a data frame. The format is of:

"%Y-%b"

看上去像"2009年9月" 等.

直到现在,我一直设法找到这种方法:

Until now I have managed to find this method:

ds[order(as.Date(ds$yearmonth, format = "%Y-%b")),]

但是它只按年份排序,然后就月份而言按字母顺序排列,给了我 2009-Jan 2009-Jul 2009年6月等.我很困惑,这不是一个容易解决的问题.

But it only sort by year, and then it moves to alphabetical order regarding the months, giving me an order of 2009-Jan, 2009-Jul, 2009-Jun etc. I am quite puzzled this is not an easy problem to fix.

请帮助...

最佳卡巴斯尔

推荐答案

中的 as.yearmon()函数(和"yearmon" 类)> zoo 专为此类数据而设计:

The as.yearmon() function (and the "yearmon" class) in package zoo is designed for this sort of data:

dat <- c("2009-Sep","2009-Feb","2009-Jan")
require(zoo)
d2 <- as.yearmon(dat, "%Y-%b")
> sort(d2)
[1] "Jan 2009" "Feb 2009" "Sep 2009"
> order(d2)
[1] 3 2 1
> d2[order(d2)]
[1] "Jan 2009" "Feb 2009" "Sep 2009"

您当然可以在每个日期的每一天 paste0()并通过 as.Date()强制使用"Date" 类,但是对我来说, as.yearmon()似乎更自然:

You could of course paste0() a day onto each date and coerce to class "Date" via as.Date() but as.yearmon() seems more natural to me:

> as.Date(paste0(dat, "-01"), "%Y-%b-%d")
[1] "2009-09-01" "2009-02-01" "2009-01-01"

请注意,您可以通过将"yearmon" 对象强制为类"as.Date" 来生成相同的结果,例如:

Note you can generate that same result by coercing the "yearmon" object to class "as.Date", e.g.:

> as.Date(d2)
[1] "2009-09-01" "2009-02-01" "2009-01-01"

这篇关于按年和月对年-月列进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆