List All Files with Specific Extension in R (Example) | list.files Function
In this tutorial, I’ll illustrate how to return a list with all file names of a directory containing a certain pattern in R programming.
The content looks as follows:
- Constructing Example Data
- Example: Get List of Certain Files in Directory [list.files Function]
- Video, Further Resources & Summary
So now the part you have been waiting for – the example!
Constructing Example Data
Before we can jump into the R programming code, we need to create a working directory that we can use for the example.
The example folder that I’m going to use looks as follows:
Figure 1: Exemplifying Folder with Different File Types.
Figure 1 illustrates the example folder we’ll use. However, you can apply the following R code to any working directory you want.
Now, let’s move on to the R code…
Example: Get List of Certain Files in Directory [list.files Function]
Let’s assume that we want to create a list of all files with an xlsx extension in our working directory. Then we can apply the list.files function as follows:
xlsx_files <- list.files(path = "C:/Users/Joachim/Desktop/example_dir", # Specify path pattern = "xlsx") # Specify pattern
We simply had to specify the path to our working folder and the pattern we are looking for within the list.files function. Now, we can print the output of the function to the RStudio console:
xlsx_files # Print list to console # "excel_1.xlsx" "excel_2.xlsx" "excel_3.xlsx"
As you can see, our example folder contains the three xlsx files excel_1.xlsx, excel_2.xlsx, and excel_3.xlsx.
You may replace the pattern argument within the list.files Function to whatever character pattern you need.
Video, Further Resources & Summary
Have a look at the following video of my YouTube channel. In the video tutorial, I explain the topics of the present tutorial.
Please accept YouTube cookies to play this video. By accepting you will be accessing content from YouTube, a service provided by an external third party.
If you accept this notice, your choice will be saved and the page will refresh.
Furthermore, I can recommend to have a look at the other articles of this website.
This tutorial showed how to use R to extract all files with a specified extension. Let me know in the comments below, if you have further questions.
Statistics Globe Newsletter