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:
- Set the working directory to the Project directory using RStudio or
- Build relative paths to anywhere within your project using
This post extends on the problem and on these two solutions.
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() ##  "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() ##  "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
Alternatively, you can leave the default untouched and build relative paths using
bad_path <- "content/post/R/dummy.R" bad_path ##  "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 ##  "C:/Users/LeporeM/Documents/Dropbox/git/fgeo.blog/content/post/R/dummy.R" readLines(good_path) ##  "# Success!!!"