Manage project files

Why manage project files?

Organising your files into directories (folders) has the following advantages:

  1. πŸ” Using the same structure for all your projects makes it easier to find files
  2. πŸ“ That familiarity makes it easier to write code which references files (data or output)
  3. πŸ‘ Projects are self-contained, so they can be moved without breaking your code
  4. πŸ‘ This means you can share your projects more easily with colleagues and collaborators

Why use the here package?

The here package enables you to reference files relative to the top-level directory, regardless of where that project directory is on your computer, or the cloud

For those familiar with R, if you use the here package, you never have to use getwd(), setwd() or file.path() again!

Install the here package

Install and load the here package with:

install.packages("here")
library(here)

Set up your project

Your main project directory needs to contain an empty file called .here. This should be created automatically by RStudio when you save your project

Use the here() function to check that your over-arching project directory is recognised correctly

here() # Should return your top-level (parent) project directory

Set up scripts

At the top of every script, include a line which specifies the location of that script

For example, if your project directory is called LeafProject, tell R where the script file is *within that parent directory

here::i_am("/scripts/import-leaf-data.R")

Declaring the location of the script to R means that you will:

  1. Get a reassuring message when you run a script, confirming the top-level project, and
  2. Get an error message if the script has been moved to a different location

Use here() inside other functions

Now when you need to reference a file within another function, you can use relative file paths

Here’s an example with the readr package’s read_tsv() function, for importing data in text files

1read_tsv(
2  here(
3    "/data/raw_data",
4  "observations.txt"))
1
Read a data file…
2
using the here() function to…
3
specify which folder to look in, inside your top-level project directory, and…
4
specify the name of the file to read