Extract File & Directory Name from Path in R (2 Examples)
In this tutorial, I’ll show how to find a file and directory name in a path in the R programming language.
The article will consist of the following:
Let’s dive right in:
Creation of Example Data
Let’s first define our directory path as a data object in R:
file_path <- "C:/Users/Joach/Desktop/my directory/my file.txt" # Example path file_path # Print example path # [1] "C:/Users/Joach/Desktop/my directory/my file.txt"
As you can see based on the previous output of the RStudio console, our example data is stored as TXT file in a folder called “my directory”.
Let’s extract these file and folder names systematically!
Example 1: Find Directory Name from Path Using dirname() Function
This example shows how to return only the directory name from our path using the dirname function.
For this, we simply have to apply the dirname function to our path object that we have created before. The dirname function automatically removes the file name and returns on the directory path:
dirname(file_path) # Apply dirname function # [1] "C:/Users/Joach/Desktop/my directory"
Example 2: Find File Name from Path Using basename() Function
This example illustrates how to show only the name of our file by applying the basename function to our path object:
basename(file_path) # Apply basename function # [1] "my file.txt"
The RStudio console has returned the name of our file, i.e “my file.txt”.
Video, Further Resources & Summary
Have a look at the following video of my YouTube channel. In the video, I explain the topics of this article.
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.
In addition, you could read the related tutorials of this homepage:
- Get & Set Working Directory in R
- Read All Files in Directory & Apply Function to Each Data Frame
- Change Default Working Directory in R & RStudio
- Set Working Directory to Source File Location Automatically vs. Manually in RStudio
- Check in R if a Directory Exists and Create if It doesn’t
- R Programming Examples
In summary: In this article you have learned how to extract a file and directory name from a path in the R programming language. Please let me know in the comments below, in case you have additional questions. Besides that, please subscribe to my email newsletter in order to receive regular updates on new articles.
Statistics Globe Newsletter