3.9 Create subdirectories

Your tutorial work may involve creating and saving outputs like figures or files, in which case you should have sub-directories for these purposes in your root directory. See the example provided in the Procedures and Guidelines document.

Let’s illustrate the procedure by creating a subdirectory called “figures”, and this time we’ll use R to create the directory.

The following code will create a directory called “figures” in your working directory

dir.create("figures")

You should see the new folder appear in the files panel on the bottom right of RStudio.

Whenever you wish to generate figures in R, then export them as image files, for example, you can save them to this folder. We’ll learn about this later.

Reading and writing files from / to directories requires that we can tell R exactly where to find those directories. That’s where the handy package called here comes in.

3.9.1 The here package

Now we’ll install and load an R package called here that will help with file and directory management and navigation.

install.packages("here")

This is a helpful blog post about the utility of the here package.

Then we load the package:

library(here)

When you load the package, the here function takes stock of where your RStudio project file is located, and establishes that directory as the “working directory”. It should return a file path for you. In future tutorials we’ll make use of the here package when saving files.