The list.files() function in R used to list out every file in specific folder.
The following methods show how you can do it with syntax.
Method 1: List All Files Using list.files() Function
list.files(path_of_folder)
Method 2: List Files With Specific Extension
list.files(file_path,pattern="csv")
Method 3: List First N Files in Folder
list.files(file_path)[1:n]
The following examples show how to use list.files() function in R.
List All Files in Folder
If I want to list all the files in the CSV_data folder, we can achieve this using the list.files() function:
# Get list of all files in folder
l <- list.files("CSV_data")
# Print list of files
print(l)
Output:
[1] "Machine_data.csv" "product.csv" "sample.tsv" "sample1.csv"
The output shows list of all files in CSV_data folder.
To get count of all files in specific folder you can use length() function:
# Get number of all files in folder
l <- length(list.files("CSV_data"))
# Print count of files
print(l)
Output:
[1] 4
As the output shows count of all files in CSV_data folder.
List All Files With Specific Extension
Let’s list all CSV files in CSV_data folder using pattern argument:
# Get CSV files from folder
l <- list.files("CSV_data",pattern = "csv")
# Print list of files
print(l)
Output:
[1] "Machine_data.csv" "product.csv" "sample1.csv"
Her the output shows list of all CSV files in CSV_data folder.
List First N Files in Folder
Let’s see example to get first 3 files from CSV_data folder:
# Get first N files from folder
l <- list.files("CSV_data")[1:3]
# Print list of files
print(l)
Output:
[1] "Machine_data.csv" "product.csv" "sample.tsv"
The output shows list of first 3 files from CSV_data folder.
By using this syntax you can get list of files from specific folder that you want.