How to sort files list by date?
Note that you can also sort by accessed time
or creation time
.
Here's a convenient, parallelized function that can handle whatever you like.
sort_files_by_date <- function(folder_path = '.', search_pattern = NULL, by = 'mtime'){
require(furrr)
require(magrittr)
require(stringr)
require(tidyverse)
if (!by %>% str_detect('^(m|a|c)time$')) {
stop('Argument `by` must be one of "mtime", "atime", or "ctime".')
}
file_names <-
# Gets all the file paths for a given path and pattern
list.files(path = folder_path, pattern = search_pattern, full.names = TRUE) %>%
# Turns into a one-column tibble (see below)
tibble(file_names = .)
files_by_datetime <-
suppressWarnings(
future_map_dfr(
.x = file_names,
.f = file.info,
.progress = TRUE,
extra_cols = FALSE # passed to file.info for performance boost
)
) %>%
# gets expanded file info, then select the last-modified time and last-accessed time
select(mtime, atime, ctime) %>%
# reintroduce our original 'file_names'
bind_cols(file_names) %>%
# arrange by descending time (depending on the users choice)
arrange(
desc(
case_when(
(by == 'mtime') ~ mtime,
(by == 'atime') ~ atime,
(by == 'ctime') ~ ctime
)
)
)
return(files_by_datetime)
}
You can use the file.info
function to obtain details on your files. Once you have those details, you can sort the files accordingly. For example,
details = file.info(list.files(pattern="*.csv"))
gives a data frame containing, inter alia, modification and creation times. You can sort that data frame however you want. Here I sort according to modification time, mtime
:
details = details[with(details, order(as.POSIXct(mtime))), ]
files = rownames(details)