Create Directory & File Path in R (2 Examples) | file.path() Function

 

This tutorial illustrates how to concatenate path components using the file.path function in the R programming language.

Table of contents:

Let’s jump right to the examples…

 

Example 1: Create Directory Path Using file.path() Function

In Example 1, I’ll demonstrate how to create a directory path using the file.path function in R.

For this, we simply have to specify all elements of our path as character strings within the file.path function:

my_directory <- file.path("C:", "Users", "Joach", "Desktop")       # Create directory path
my_directory
# [1] "C:/Users/Joach/Desktop"

As you can see based on the previous output of the RStudio console, we have created a new data object called my_directory, which contains the path to a folder on our computer.

Note that this path was created in a platform-independent way, i.e. the file.path function provides proper operating system (OS) path format detection. The previous code works on Microsoft Windows, as well as on Apple macOS, and Linux.

 

Example 2: Create File Path Using file.path() Function

We can also use the file.path function to create a path to a specific file in a working directory.

Consider the following R code:

my_file <- file.path("C:", "Users", "Joach", "Desktop", "my_file.csv")  # Create file path
my_file
# [1] "C:/Users/Joach/Desktop/my_file.csv"

As you can see, we have created a new data object called my_file, which contains the path to a particular file.

 

Video & Further Resources

I have recently released a video on my YouTube channel, which illustrates the R syntax of this article. You can find the video below:

 

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.

YouTube Content Consent Button Thumbnail

YouTube privacy policy

If you accept this notice, your choice will be saved and the page will refresh.

 

Furthermore, you may read the other tutorials on this homepage.

 

You have learned in this article how to manage path components and construct a path using the file.path function in the R programming language. Let me know in the comments, if you have additional questions.

 

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.

Menu
Top