Mohammad Mohammad - 3 months ago 24
R Question

How to sort the date inside a string?

I have a few file names which include dates and I need to sort them in numerical order, for example:


and I want to sort it out to:

> dates
"8_4_2016.xlsx" "8_18_2016.xlsx" "8_25_2016.xlsx"



One way would be to find the order by creating a separate vector, where the values are converted to date format:

dates.order <- order( as.Date( dates, format = "%m_%d_%Y.xlsx" ) )

Then use that to sort your original vector:

sorted <- dates[ dates.order ]
[1] "8_4_2016.xlsx"  "8_18_2016.xlsx" "8_25_2016.xlsx"