matandked matandked - 2 months ago 13
R Question

Sort vector of strings based on part of string (date) in R

I have vector of strings in R! which stores file names.

File names contains date stored in following format: 'YYYYMMDD'.
Sample file names are as follows:


I would like to sort list using date from file name (so that files for the earliest date will be the first in the vector).
Unfortunately, sort function in R! doesn't have any 'regex' sorting criteria parameter. How should I do that?

My sample data:

files <- c("",


This should work:


edit: same approach as everyone. Extract the dates, turn them into a date format, then use them to reorder files.
The idea behind the regex is to extract a series of 8 numbers ([0-9]{8}) that occurs after a _ symbol ((?<=_))