我有一个数据集,其日期列如下:
dateCol other column
"2013/11/12" some data
"2012/05/02" more data
"2013/09/22" etc
"" etc
"2013/09/17" etc
当我尝试按日期按此列(dateCOl)订购数据框时,它什么也没做,我尝试了几个代码,我的最后一个代码是:
mydata<-mydata[with(mydata, order(as.Date(mydata[,dateCol], format="%y/%m/%d"))),]
但是没有工作,有什么想法吗?
提前致谢!
答案 0 :(得分:2)
您需要提供正确的转换日期格式才能成功转换。在这种情况下,对于包含几个世纪的年份数据,您需要"%Y"
,其首都为Y
。
尝试
sort(as.Date(mydata[,"dateCol"], format="%Y/%m/%d"))
#[1] "2011-07-13" "2011-08-21" "2012-05-02" "2012-07-02" "2012-07-17" "2013-01-29"
#[7] "2013-08-19" "2013-09-17" "2013-09-22" "2013-11-12" "2014-04-02"
数据强>
mydata <-structure(list(dateCol = structure(c(1L, 11L, 4L, 10L, 1L, 1L,
1L, 1L, 1L, 9L, 6L, 5L, 12L, 1L, 1L, 8L, 1L, 7L, 3L, 2L),
.Label = c("", "2011/07/13", "2011/08/21", "2012/05/02",
"2012/07/02", "2012/07/17", "2013/01/29", "2013/08/19",
"2013/09/17", "2013/09/22", "2013/11/12", "2014/04/02"),
class = "factor")), .Names = "dateCol",
row.names = (NA, -20L), class = "data.frame")