Working with file paths

Paths can be absolute (/Users/blabber/Documents/data.csv) or relative (data.csv). When you use relative paths, the program needs to know what directory they are relative to. We call that directory (/Users/blabber/Documents/) the working directory.

Knit Directory

When you knit an R-Markdown file in RStudio, you can set the "Knit Directory" - the working directory that will be used when knitting the document. Among other things, every relative path will be considered to be relative to that folder. So, when you write read_csv('data/penguins.csv'), R will look for `data/penguins.csv` in that directory.

It can be set to the "Project Directory" (commonly used in BLab), to the "Document Directory" (commonly used outside of BLab) or "Current Working Directory" (at times, useful as a temporary setting). Instead of relying on everyone having "Knit Directory" set to the same option in RStudio, we should define paths in a way that is agnostic to that setting.

here and fs::path

One way to do this is to use package here and function fs::path. We will use here to find folders within our project folder and we will use fs::path to construct path to files in relation to these folders. Like this:

data_folder <- here::here('data')
ant_info <- read_csv(fs::path(data_folder, 'ant_info.csv'))

Do not use library(here) because it prints out the absolute path to the project folder which will be user-specific and will produce unnecessary changes to the knit notebooks.

Last updated