0

When working inside an R project, I like to use relative paths, relative to the root of the project directory. Since a couple of weeks, I have upgraded RStudio to the latest version which includes "R Notebooks".

Notebooks are great but the options which I used in my knitr documents doesn't work any more:

opts_knit$set(root.dir="../..")

I would like paths to be relative to the project directory and I don't want to use setwd() because this wouldn't give the same result in interactive mode and in knitting mode. Also I like to be able to source the entire knitr document multiple times and changing to a relative directory setwd("..") multiple times quickly leads to an undesired path.

As suggested by Jennifer Bryan, is it necessary to use a package simply to set relative paths to files inside a project?

Paul Rougieux
  • 10,289
  • 4
  • 68
  • 110
  • The general wisdom is to avoid using `setwd` outside of the console. I generally put paths as relative to the project directory, and if that fails because I'm calling it from the wrong directory, that's my fault (and easily rectified). A more robust solution would require more work, like a package or makefile. – alistaire Feb 16 '17 at 00:19
  • This question concerns the same issue: [opts_knit$set(root.dir = path) does not work after RStudio upgrade 1.0.44](http://stackoverflow.com/questions/40717410/opts-knitsetroot-dir-path-does-not-work-after-rstudio-upgrade-1-0-44). An answer links to a [R_Notebook help page](http://rmarkdown.rstudio.com/r_notebooks.html#executing_code) that suggests using `knitr::opts_knit$set(root.dir = normalizePath(".."))` in a "setup" chunk. – Paul Rougieux Feb 16 '17 at 00:23
  • @alistaire thanks. Let's say that I have a Rmd document in my project's subfolder `./docs/experiment.Rmd`. In order to use paths relative to the project directory, I need to set the knitr option `opts_knit$set(root.dir="..")` inside the markdown file `experiment.Rmd` so that I can use paths relative to the project directory in that document. The issue is that this approach doesn't work with R Notebooks. – Paul Rougieux Feb 16 '17 at 00:30
  • @Yihui It seems the knitr chunk in which `opts_knit$set(root.dir="..")` is placed has to be called `setup` for this instruction to work. Is that normal? Or there is some caching going on that prevents the first chunk from being executed. – Paul Rougieux Feb 16 '17 at 00:46

0 Answers0