首页 > 解决方案 > R:将动态日期格式转换为日期类?

问题描述

我有一个数据集,其中包含一个由日期组成的简单列,如下所示:

      Dates
1  2012/04/10
2  2012/03/30
3  2012/03/24
4  2012/03/25
5  2012/04/10
6  2012/04/14
7  2012/04/21

我想要的输出是这样的:

      Dates        DateName
1  2012/04/10     April 2012
2  2015/03/30     March 2015
3  2011/03/24     March 2011
4  2016/12/25     December 2016
5  2014/06/10     June 2014
6  2014/05/14     May 2014
7  2018/07/21     August 2018

为此,我使用了以下代码:

dt$Dates <- as.Date(dt$Dates)
dt$DateName <- format(dt$Dates,"%B %Y")

虽然这很好用,但我的新专栏出现了一个字符类。我希望这可以作为约会课程出来。这是因为我无法按日历日期对该列进行排序。相反,它按字母顺序排序。

有没有办法将我的新日期格式归类或重新归类为某种日期或日历类?

(我不一定要寻找 base-R 解决方案)。

(如果可能的话,我也非常希望保持我的新格式不变)。

我已经尝试了以下代码行等,但这些只返回错误。

dt$DateName <- format.Date(dt$Dates,"%B %Y")

dt$DateName <- format.POSIXlt(dt$Dates,"%B %Y")

dt$DateName <- format.difftime(dt$Dates,"%B %Y")

dt$DateName <- as.Date(dt$Dates, format ="%B %Y")

标签: rclassdatecalendarlubridate

解决方案


您可以将日期转换为yearmon类:

dt$month_year <- zoo::as.yearmon(dt$Dates, "%Y/%m/%d")
dt
#       Dates month_year
#1 2012/04/10   Apr 2012
#2 2012/03/30   Mar 2012
#3 2012/03/24   Mar 2012
#4 2012/03/25   Mar 2012
#5 2012/04/10   Apr 2012
#6 2012/04/14   Apr 2012
#7 2012/04/21   Apr 2012

class(dt$month_year)
#[1] "yearmon"

然后你可以对它们进行排序

dt[order(dt$month_year), ]

#       Dates month_year
#2 2012/03/30   Mar 2012
#3 2012/03/24   Mar 2012
#4 2012/03/25   Mar 2012
#1 2012/04/10   Apr 2012
#5 2012/04/10   Apr 2012
#6 2012/04/14   Apr 2012
#7 2012/04/21   Apr 2012

数据

dt <- structure(list(Dates = structure(c(4L, 3L, 1L, 2L, 4L, 5L, 6L
), .Label = c("2012/03/24", "2012/03/25", "2012/03/30", "2012/04/10", 
"2012/04/14", "2012/04/21"), class = "factor")), class = "data.frame",
row.names = c("1", "2", "3", "4", "5", "6", "7"))

推荐阅读