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.



In addition, you could read the related tutorials of this homepage:


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.


Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.