0

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") 
2
  • Try sort(as.Date(date, "%b %d, %Y")). Commented Mar 12, 2015 at 18:28
  • 1
    Did you actually look into ?as.Date documentation? Plenty of similar examples there. Commented Mar 12, 2015 at 18:36

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

yeah I did look at as.Date documentation. Apparently I had few extra spaces in my date so had to modify the format=" %b %d, %Y".
@user24318: If spacing is giving you an issue you can replace multiple spaces with a single space using gsub(). But if modifying the format works fine for you then gsub() is probably unnecessary.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.