You can use the list.files() function in R to list out every file in a specific folder.
The following examples show how to use this function in different scenarios with a folder called my_data_files that contains three CSV files and two TXT files:
Example 1: List All Files in Directory
We can use the following syntax to list out every file in this folder:
#display all files in my_data_files folder list.files('C:/Users/bob/Documents/my_data_files') [1] "df1.csv" "df2.csv" "df3.csv" "more_data.txt" "some_data.txt"
We can see the names of all five files in this folder.
We could also use the length() function if we just wanted to know how many files were in the folder:
#display total number of files in my_data_files folder length(list.files('C:/Users/bob/Documents/my_data_files')) [1] 5
Example 2: List First N Files in Directory
We can use the following syntax to list out just the first three files in this folder:
#display first three files in my_data_files folder list.files('C:/Users/bob/Documents/my_data_files')[1:3] [1] "df1.csv" "df2.csv" "df3.csv"
We can see the names of just the first three files in this folder.
Example 3: List All Files in Directory with Specific Extension
We can also use the pattern argument to only list the files that have a specific extension:
#display all files with CSV extension in my_data_files folder list.files('C:/Users/bob/Documents/my_data_files', pattern='csv') [1] "df1.csv" "df2.csv" "df3.csv"
We can see all three files that have a .csv extension.
Example 4: List All Files in Directory that Contain String
We can also use the pattern argument to only list files that contain a certain string:
#display all files that contain 'data' in file name list.files('C:/Users/bob/Documents/my_data_files', pattern='data') [1] "more_data.txt" "some_data.txt"
We can see the two files that both contain ‘data’ in the file name.
Additional Resources
The following tutorials explain how to perform other common tasks in R:
How to Import CSV Files into R
How to Import a CSV from URL in R
How to Import Excel Files into R