在R数据框中如何按年份和月排序? [英] How to sort by year AND month in R data frame?

查看:519
本文介绍了在R数据框中如何按年份和月排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

"%Y-%b"

其中看起来像2009-Sep等。

到目前为止,我已经设法找到这种方法:

Until now I have managed to find this method:

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

但是它只按年份排序,然后按照字母顺序排列月份,给我一个订单 2009-Jan 2009 -Jul 2009-Jun 等我很困惑,这不是一个容易解决的问题。

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.

请帮助...

最佳
Kasper

Best Kasper

推荐答案

包中的 as.yearmon()函数(和yearmon类) 动物园是为这种数据设计的:

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"

您可以在每个日期的某一天($ code)paste0(),并胁迫到Date通过 as.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"

这篇关于在R数据框中如何按年份和月排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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