Home » How to Use file.path() Function in R (With Example)

How to Use file.path() Function in R (With Example)

by Erma Khan

The file.path() function in base R offers a convenient way to define a file path.

This function uses the following basic syntax:

file.path(“C:”, “Users”, “bob”, “Data_Science_Documents”, fsep=”\”)

The following example shows how to use this function in practice.

Example: How to Use file.path() Function in R

Suppose I would like to set the following directory as my working directory in R:

  • C:UsersbobData_Science_Documents

I can use the following syntax with the file.path() function to do so:

#define file path
path path("C:", "Users", "bob", "Data_Science_Documents", fsep="\")

#view file path
path

[1] "C:\Users\bob\Data_Science_Documents"

#set path as working directory
setwd(path)

The working directory is now set to the following location:

  • C:UsersbobData_Science_Documents

I can confirm this by using the getwd() function to get the current working directory:

#get path of current working directory
getwd()

[1] "C:/Users/bob/Data_Science_Documents"

It’s worth noting that you could also manually type out the slashes in the file path location to set the working directory.

However, the file.path() function offers an easier way to define a file path with fewer characters.

The file.path() function also offers more readable code and is a function included in base R, so you don’t have to load any external packages to use it.

Additional Resources

The following tutorials explain how to perform other common tasks in R:

How to Check if a Package is Installed in R
How to Check if a Directory Exists in R
How to Load Multiple Packages in R

Related Posts