Skip to contents

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.

Usage

sort_files_by_size(files, decreasing = FALSE, root = NULL)

Arguments

files

A character vector of file paths.

decreasing

(optional) A logical flag 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 
#>  "319.5K"  "331.4K"  "386.1K"   "75.4K"  "183.1K" 

sort_files_by_size(files, root = dir)
#> file4.txt file5.txt file1.txt file2.txt file3.txt