Organising your files into directories (folders) has the following advantages:
π Using the same structure for all your projects makes it easier to find files
π That familiarity makes it easier to write code which references files (data or output)
π Projects are self-contained, so they can be moved without breaking your code
π This means you can share your projects more easily with colleagues and collaborators
Recommended directory structure
π leaf_project
πleaf-data.Rproj
π data
π raw_data
π’leaf-data.txt
π processed_data
π’clean-leaf-data.RData
π outputs
πreport.txt
πfigure_1.png
π scripts
π€clean-data.R
π€create-plots.R
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:
Get a reassuring message when you run a script, confirming the top-level project, and
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