R list.files recursive
Walk a directory tree and select matching regular files.
A simple example
list.files recursive
- Start with Folder a contains b/c.txt
- Do this Visit descendants
- Result The walk reaches c.txt
Syntax
list.files(base, recursive = TRUE)
Run these examples in R
Save one example at a time as Lesson.R. Use R 4.x.
Rscript --vanilla Lesson.RFind a receipt below the month folder
A treasurer has one receipt in a month folder and a note beside that folder. A recursive inventory should locate the nested CSV receipt while leaving the unrelated note out of its total.
run_example <- function() {
base <- tempfile("lesson-")
stopifnot(dir.create(base))
on.exit(unlink(base, recursive = TRUE))
stopifnot(dir.create(file.path(base, "March")))
stopifnot(file.create(file.path(base, c("March/dues.csv", "notes.txt"))))
cat(length(list.files(base, pattern = "[.]csv$", recursive = TRUE)), "\n", sep = "")
}
run_example()
1
The month folder contributes one matching receipt below the top level.
Inventory class submissions
A teacher receives two top-level files and one file in a team folder. Count regular files throughout the folder tree, including its subfolders.
Inventory rehearsal parts
A school stores one score and two parts in a subfolder. Count regular files throughout the folder tree, including its subfolders.
What to watch for
Following symbolic links during recursion can revisit directories. Choose link handling deliberately.