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" |
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" |
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:
The YouTube video will be added soon.
Furthermore, you may read the other tutorials on this homepage.
- Get & Set Directory Path of Installed Packages Using libPaths Function
- Check in R if a Directory Exists and Create if It doesn’t (Programming Example)
- Extract File & Directory Name from Path
- Introduction to System Calls & Commands
- Useful Functions in R (Example Codes)
- R Programming Tutorials
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.
Statistics Globe Newsletter