Base R offers access to directory listings through list.files()
and list.dirs()
.
By default, list.files()
lists all files in the current working directory, returning a character vector.
list.files() [1] "file-eight.csv" "file-five.ods" "file-four.rtf" "file-nine.docx" "file-one.txt" [6] "file-seven.csv" "file-six.odt" "file-ten.tex" "file-three.rtf" "file-two.txt"
Use the path =
argument to specify a directory to pass to list.files()
.
list.files(path = '/home/jsmith/subdir/') [1] "s-file-five.ods" "s-file-four.rtf" "s-file-one.txt" "s-file-three.rtf" [5] "s-file-two.csv"
The all.files =
argument can be used to specify whether to expose hidden files. By default, all.files = F
.
list.files(path = '/home/jsmith/subdir/') [1] "s-file-five.ods" "s-file-four.rtf" "s-file-one.txt" "s-file-three.rtf" [5] "s-file-two.csv" list.files(path = 'subdir/', all.files = T) [1] "." ".." ".git" "s-file-five.ods" [5] "s-file-four.rtf" "s-file-one.txt" "s-file-three.rtf" "s-file-two.csv"
The current (".") directory and parent ("..") directory can be excluded by using the no.. =
argument. By default, no.. = F
.
list.files(path = 'subdir/', all.files = T, no.. = T) [1] ".git" "s-file-five.ods" "s-file-four.rtf" "s-file-one.txt" [5] "s-file-three.rtf" "s-file-two.csv"
The pattern =
argument allows you to specify a regular expression pattern in order to return particular files.
# return CSV files in current directory list.files(path = '.', pattern = '\\.csv$') [1] "file-eight.csv" "file-seven.csv" # return RTF and DOCX files in current and all subdirectories list.files(path = '.', recursive = T, pattern = '(\\.rtf$|\\.docx)$') [1] "file-four.rtf" "file-nine.docx" "file-three.rtf" [4] "subdir/s-file-four.rtf" "subdir/s-file-three.rtf"
To return full path names of files, include the full.names = T
argument.
This works by prepending the path name to the listed files.
list.files(path = '/home/jsmith/subdir/', full.names = T, recursive = T) [1] "/home/jsmith/subdir/s-file-five.ods" [2] "/home/jsmith/subdir/s-file-four.rtf" [3] "/home/jsmith/subdir/s-file-one.txt" [4] "/home/jsmith/subdir/s-file-three.rtf" [5] "/home/jsmith/subdir/s-file-two.csv"