【问题标题】:Sort "year/mon" column in R在R中对“年/月”列进行排序
【发布时间】:2014-04-11 00:50:03
【问题描述】:

我试图在 R 中按“year.month”列对数据框进行排序,但停留在“as.Date”函数中。我尝试了其他几种方法,但没有成功。我能得到一些帮助吗? 这里是。 我的代码是

temp2_sort <- temp2[with(temp2, order(as.Date(year.month, format = "%y-%m"))),]
or 
temp2_sort <- temp2[with(temp2, order(as.Date(year.month, format = "%y-%b"))),]

但它们都不起作用。

谢谢!

year.month  sale
2006/2  437
2006/3  52299
2006/9  175983
2006/12 57560
2007/2  10798
2007/3  12926
2006/5  61039
2006/8  135601
2006/6  54336
2006/10 72052

【问题讨论】:

  • 当您的年份为 YYYY 时,格式规范必须为“%Y”
  • 我试过 %Y、%y、%YYYY、%yyyy 等,在这种情况下它们的行为都一样。
  • 该列可能是一个因素,您需要使用 as.character()。
  • 感谢您的细心考虑;我确实将此列转换为字符,但排序仍然不正确。

标签: r sorting date


【解决方案1】:

使用lubridate

 dat[order(ymd(dat$year.month)),]

使用as.Date 你应该添加一个虚拟的一天部分:

dat[order(as.Date(paste0(dat$year.month,'/1'),"%Y/%m/%d")),]

【讨论】:

    猜你喜欢
    • 2013-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多