How to Work with Files and Folders in R

By Andrie de Vries, Joris Meys

You know how to import your data into R and export your data from R. Now all you need is an idea of where the files are stored with R and how to manipulate those files. Every R session has a default location on your operating system’s file structure called the working directory.

You need to keep track and deliberately set your working directory in each R session. If you read or write files to disk, this takes place in the working directory. If you don’t set the working directory to your desired location, you could easily write files to an undesirable file location.

The getwd() function tells you what the current working directory is:

> getwd()
[1] "F:/git"

To change the working directory, use the setwd() function. Be sure to enter the working directory as a character string (enclose it in quotes).

This example shows how to change your working directory to a folder called F:/git/roxygen2:

> setwd("F:/git/roxygen2")
> getwd()
[1] "F:/git/roxygen2"

Notice that the separator between folders is forward slash (/), as it is on Linux and Mac systems. If you use the Windows operating system, the forward slash will look odd, because you’re familiar with the backslash () of Windows folders. When working in Windows, you need to either use the forward slash or escape your backslashes using a double backslash (\). Compare the following code:

> setwd("F:\git\stringr")
> getwd()
[1] "F:/git/stringr"

R will always print the results using /, but you’re free to use either / or \ as you please.

To avoid having to deal with escaping backslashes in file paths, you can use the file.path() function to construct file paths that are correct, independent of the operating system you work on. This function is a little bit similar to paste in the sense that it will append character strings, except that the separator is always correct, regardless of the settings in your operating system:

> file.path("f:", "git", "surveyor")
[1] "f:/git/surveyor"

It’s often convenient to use file.path() in setting the working directory. This allows you specify a cascade of drive letters and folder names, and file.path() then assembles these into a proper file path, with the correct separator character:

> setwd(file.path("F:", "git", "roxygen2"))
> getwd()
[1] "F:/git/roxygen2"

You also can use file.path() to specify file paths that include the filename at the end. Simply add the filename to the path argument. For example, here’s the file path to the file in the roxygen2 package installed in a local folder:

> file.path("F:", "git", "roxygen2", "roxygen2", "" )
[1] "F:/git/roxygen2/roxygen2/"