Mohammad Mohammad - 1 month ago 12
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:

dates=c("8_18_2016.xlsx","8_25_2016.xlsx","8_4_2016.xlsx")


and I want to sort it out to:

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


Thanks

Answer

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 ]
sorted
[1] "8_4_2016.xlsx"  "8_18_2016.xlsx" "8_25_2016.xlsx"
Comments