The here package enables easy file referencing by using the top-level directory of a file project to easily build file paths. This is in contrast to using
setwd(), which is fragile and dependent on the way you order your files.
The package displays the top-level of the current project on load:
or any time you call here()
You can build a path relative to the top-level directory in order to read or write a file:
This works regardless of where the associated source file lives inside your project. This is especially helpful if you use RMarkdown with the default behaviour, where the working directory is the directory where the file is.
Consider the following directory:
├── analysis │ └── report.Rmd ├── data │ └── data.csv ├── project.Rproj
The working directory is for
report.Rmd is the
analysis/ subdirectory, while
data.csv lives in the
report.Rmd, you would have to ensure the path to
data.csv is relative to the
analysis/ directory - i.e.,
../data/data.csv. The chunks would knit properly, but could not be run in the console since the working directory in the console isn’t
The here package circumvents this issue by always creating the file path relative to the top level directory, so that
data.csv can be read using
here("data", "data.csv") both when the report is knit and when the code is run interactively in the console.