Reputation: 485
I have a data set that has dates in the following format. There are some repeated dates too. I need to sort the data according to the dates in calendar order.
So "Sep 20, 2010", "Mar 5, 2011", "Mar 9, 2011"
and so on. I tried the following but it gives me an error.
as.Date(date)
Error in charToDate(x) :
character string is not in a standard unambiguous format
I also tried sort(date) but it sorts the date alphabetically by Month. How can I sort this type of dates in calendar order ?
date<-c("Mar 9, 2011", "Sep 30, 2011", "Sep 20, 2010", "Mar 5, 2012", "Jul 11, 2012",
"Jul 11, 2012","Mar 26, 2013", "Sep 23, 2013", "Apr 7, 2011", "Apr 22, 2013",
"Apr 26, 2012")
Upvotes: 0
Views: 3574
Reputation: 5586
What you need is the format=
argument in the as.Date()
function. So if date
is a vector defined as in your post, you can do
date <- sort(as.Date(date, format="%b %d, %Y"))
%b
is the abbreviated month name, e.g. Mar
%d
is the numeric day of the month
%Y
is the year
Using the sort()
function should then correctly sort the vector ascending by calendar date.
Upvotes: 1