9.2 The working directory

A working directory is like a flag on your computer that tells R where to start looking for your files related to a specific project. Each project should have its own folder with organized sub-folders.

Figure 9.3: A working directory is like a flag on your computer that tells R where to start looking for your files related to a specific project. Each project should have its own folder with organized sub-folders.

The working directory is just a file path on your computer that sets the default location of any files you read into R, or save out of R. In other words, a working directory is like a little flag somewhere on your computer which is tied to a specific analysis project. If you ask R to import a dataset from a text file, or save a dataframe as a text file, it will assume that the file is inside of your working directory.

You can only have one working directory active at any given time. The active working directory is called your current working directory.

To see your current working directory, use getwd():

# Print my current working directory
getwd()
## [1] "/Users/nphillips/Dropbox/manuscripts/YaRrr/YaRrr_bd"

As you can see, when I run this code, it tells me that my working directory is in a folder on my Desktop called yarrr. This means that when I try to read new files into R, or write files out of R, it will assume that I want to put them in this folder.

If you want to change your working directory, use the setwd() function. For example, if I wanted to change my working directory to an existing Dropbox folder called yarrr, I’d run the following code:

# Change my working directory to the following path
setwd(dir = "/Users/nphillips/Dropbox/yarrr")