【问题标题】:How to arrange date in R if date is in character?如果日期是字符,如何在 R 中安排日期?
【发布时间】:2019-11-25 09:45:17
【问题描述】:

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

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

如何按升序排列它们才能得到这个?

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

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

【问题讨论】:

    标签: r date


    【解决方案1】:

    一种方法是将值转换为日期,然后转换为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'))
    

    【讨论】:

      猜你喜欢
      • 2022-01-22
      • 1970-01-01
      • 2012-05-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-08
      • 1970-01-01
      • 2015-04-05
      相关资源
      最近更新 更多