r - 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")
解决方案
您可以将日期转换为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"))
推荐阅读
- javascript - 尝试使用 Vue.js 访问 Stack Oveflow Api 出现错误
- android - 如何修复无法读取序列化文件指纹。在数据流中发现无法识别的值
- python - Django 无法登录用户
- python - 您可以自行签署 pyinstaller 程序,以便在将其提供给其他人时不会显示为病毒吗?
- java - 下载文件android的异常
- docker - Traefik 2 - 尝试将我的第一个容器配置为使用 traefik
- c# - 重新加载时重置分数
- javascript - JavaScript p5.js 游戏中的敌人检测和炮塔动画/控制
- android - 使用浮动或分数样式资源的自定义视图崩溃
- c++ - 与串行版本相比,使用 openMP 的插入排序的并行化给出了非常尖锐的结果