The annoying thing is that if the paths are generated usually, you won’t be able to run them on some other operating system. The R language provides a file.path()
function capable of generating paths in a platform-independent manner. This article will describe the syntax and usage of file.path
in R. Let’s get started.
The file.path() function in R
The file.path()
function in R is used to construct paths to files and directories from components.
The syntax of the file.path()
function in R has the following form:
file.path(…, fsep)
Parameters:
- …: character vectors representing path components.
- fsep: the delimiter used in the output path. The default is
.Platform$file.sep
.
The file.path()
function returns a character vector consisting of concatenated and delimited elements by the value of the ‘fsep’ argument.
How to use file.path in R?
In the first example, we will use the file.path()
function to create a directory path.
Example:
# Create a directory path directory_path <- file.path("D:", "Documents", "LearnShareIT", "R") directory_path
Output:
[1] "D:/Documents/LearnShareIT/R"
You can also create a path to a specific file using the file.path()
function in R.
Example:
# Create a directory path file_path <- file.path( "D:", "Documents", "LearnShareIT", "R", "How to install RStudio.docx" ) file_path
Output:
[1] "D:/Documents/LearnShareIT/R/How to install RStudio.docx"
As you can see, we have created a path to specific folders and files from the components on the Windows operating system using the file.path()
function. One thing to note here is that the file.path()
function is platform-independent, which means that the file.path()
function can generate the path in the format corresponding to the operating system.
Another function in R that is also used to concatenate character vectors is the paste()
function. However, this function is not commonly used to generate paths to files and directories because it cannot automatically generate the path corresponding to the operating system. We already have an article on how to use the paste()
function in R. Read more here.
Summary
This article shared the syntax and usage of the file.path()
function to create paths to files and directories. Because it can be platform-independent, file.path()
in R is widely used in creating paths that can be run on other operating systems, thus reducing the difficulty for the receiver of your script on another operating system. Thanks for reading.

Hello, my name’s Bruce Warren. You can call me Bruce. I’m interested in programming languages, so I am here to share my knowledge of programming languages with you, especially knowledge of C, C++, Java, JS, PHP.
Name of the university: KMA
Major: ATTT
Programming Languages: C, C++, Java, JS, PHP