sort_files_by_size() sorts a vector of file paths based on their size.
It is useful for organizing files in a directory or for preparing files
for processing.
Arguments
- files
A
charactervector of file paths.- decreasing
(optional) A
logicalflag indicating whether to sort the files in decreasing order of size (default:FALSE).- root
(optional) A string specifying the root directory of the files. If
NULL, the function will treat the paths as absolute (default:NULL).
Value
A character vectors with the file paths
sorted by size.
Examples
library(fs)
library(readr)
files <- c("file1.txt", "file2.txt", "file3.txt", "file4.txt", "file5.txt")
dir <- tempfile("dir")
dir.create(dir)
for (i in files) {
write_lines(rep(letters, sample(1000:10000, 1)), file.path(dir, i))
}
sizes <- file_size(file.path(dir, files)) |> as.character() |> trimws()
names(sizes) <- files
sizes
#> file1.txt file2.txt file3.txt file4.txt file5.txt
#> "459K" "356K" "308K" "375K" "301K"
sort_files_by_size(files, root = dir)
#> file5.txt file3.txt file2.txt file4.txt file1.txt