-2

I have a data set with a date column like this:

dateCol            other column
"2013/11/12"    some data
"2012/05/02"    more data
"2013/09/22"    etc
""              etc
"2013/09/17"    etc

When I try to order the data frame by this column(dateCOl) by date, it just does nothing, I tried several codes, my last code was:

mydata<-mydata[with(mydata, order(as.Date(mydata[,dateCol], format="%y/%m/%d"))),]

But is not working, any ideas?

Thanks in advance!

Amnor
  • 380
  • 6
  • 21

1 Answers1

2

You need to provide the right format of the dates for the conversion to succeed. In this case you need "%Y" with a capital Y for data with years including the centuries.

Try

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"

data

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")
RHertel
  • 23,412
  • 5
  • 38
  • 64
  • Thanks, that sort the column alone right, but if I do "mydata<-mydata[with(mydata,sort(as.Date(mydata[,dateRow], format="%Y/%m/%d"))),]" the column in the dataset converts to NA – Amnor Jun 08 '16 at 09:55
  • 1
    perfect, putted the capital on format, now works, thank you! – Amnor Jun 08 '16 at 09:58