首页 > 解决方案 > 如果日期是字符,如何在 R 中安排日期?

问题描述

现在我有一个名为trending_month 的列,其中包含字符值:

'Jan 2018', 'Dec 2017', 'Feb 2018', 'Nov 2017'

我如何按升序排列它们以获得这个?

'Nov 2017', 'Dec 2017', 'Jan 2018', 'Feb 2018'

由于trending_month 是字符,当我按升序排序时,它按字母格式排列。

标签: rdate

解决方案


一种方法是将值转换为 date 然后order. 在基础 R 中,可以这样完成

df[order(as.Date(paste(1, df$trending_month), "%d %b %Y")), ]

#  x trending_month
#4 4       Nov 2017
#2 2       Dec 2017
#1 1       Jan 2018
#3 3       Feb 2018

数据

df <- data.frame(x = 1:4, 
                 trending_month = c('Jan 2018','Dec 2017','Feb 2018','Nov 2017'))

推荐阅读