按“年/月"排序R中的列 [英] Sort "year/mon" column in R

查看:105
本文介绍了按“年/月"排序R中的列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试按R中"year.month"列对数据帧进行排序,但是卡在"as.Date"功能上.我尝试了其他几种方法,但没有成功.我可以帮忙吗? 这里是. 我的代码是

I am trying to sort a data frame by column of "year.month" in R, but stuck at "as.Date" function. I have tried several other ways but no success. Can I get some help? Here it is. my code is

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

推荐答案

使用lubridate:

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

使用as.Date,您应该添加一个虚拟日部分:

Using as.Date you should add a dummy day part:

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

这篇关于按“年/月"排序R中的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆