One of the awesome aspects of rmarkdown documents is that they help you avoid calls to setwd() and instead they let you use paths relative to your working directory. The problem is that the notion of working directory of an rmarkdown document may be different than what you expect. These are two ways to avoid this problem:

  1. Set the working directory to the Project directory using RStudio or
  2. Build relative paths to anywhere within your project using here::here().

This post extends on the problem and on these two solutions.

The problem

The document you are reading now is an rmarkdown document using the default working directory. Notice that it has a different notion of woking directory compared to the project’s working directory.

getwd()
## [1] "C:/Users/LeporeM/Documents/Dropbox/git/fgeo.blog/content/post"

usethis::proj_get()
## <U+2714> Setting active project to 'C:/Users/LeporeM/Documents/Dropbox/git/fgeo.blog'
## C:/Users/LeporeM/Documents/Dropbox/git/fgeo.blog

Now notice that here::here() gets is right.

usethis::proj_get()
## C:/Users/LeporeM/Documents/Dropbox/git/fgeo.blog

here::here()
## [1] "C:/Users/LeporeM/Documents/Dropbox/git/fgeo.blog"

1. Set the working directory to the Project directory using RStudio or

You can use RStudio to change this setting from Document directory to Project directory. But be careful, this setting goes back to its default every time you rename or move the rmarkdown file – so you may need to repeat this step.

2. Build relative paths to anywhere within your project using here::here().

Alternatively, you can leave the default untouched and build relative paths using here::here().

bad_path <- "content/post/R/dummy.R"
bad_path
## [1] "content/post/R/dummy.R"

# This will fail
readLines(bad_path)
## Warning in file(con, "r"): cannot open file 'content/post/R/dummy.R': No
## such file or directory
## Error in file(con, "r"): cannot open the connection
good_path <- here::here("content/post/R/dummy.R")
good_path
## [1] "C:/Users/LeporeM/Documents/Dropbox/git/fgeo.blog/content/post/R/dummy.R"

readLines(good_path)
## [1] "# Success!!!"