5

Rstudio states that:

the current working directory inside a notebook chunk is always the directory containing the notebook .Rmd file.

Understood. But if within a notebook we setwd() to something (either to "the directory containing the notebook .Rmd file" or elsewhere, doesn't matter), this doesn't set the working directory in the console, only in the notebook.

The reverse is also true, setting working directory in the console doesn't change the working directory in the notebook — though this is somewhat explained by the above.

The only way to set working directory both in the console and a notebook seems to be to run the same setwd() call in both console and notebook.

Why?

Is there any way to streamline this so that the working directory is automatically the same for both notbook and console, once a setwd() call is made, rather than confusingly having two 'parallel' working directories?

One assumes one is not alone in working from notebooks, but doing the 'dirty work' and quick checks that one has no plan to keep in the console. This working directory behaviour is therefore quite frustrating.

Scransom
  • 3,175
  • 3
  • 31
  • 51

1 Answers1

6

rmarkdown site explains this. It suggests using:

```{r setup}
    knitr::opts_knit$set(root.dir = normalizePath("path")) 
```

where path stands for the path to the working directory you want to establish.

Make sure you set your working directory within the setup chunk.

======

I believe the reason for this only changing the working directory in the notebook, but not in the console stems from the idea being it a "notebook". Once you start using the notebook, everything is in

code
output

format. So the results are shown beneath the code. There is no more need for the console. The console is kept separate, for your other needs maybe. It is similar to Jupyter. There you only have code and output cells, nothing else. It doesn't have any console nor variables sections. Clean and neat.

ilyas
  • 609
  • 9
  • 25
  • This is useful information but solves a different problem. Doing this changes the working directory in all of the chunks in the notebook only, it doesn't change the working directory in the console, which is what I'm wondering about – Scransom Nov 15 '17 at 00:28
  • 1
    One thing to note about this answer is that, from the documentation you reference **Also note that, as in knitr, the root.dir chunk option applies only to chunks**. This means that if you change the wd in a chunk and read another script that uses relative paths, R treats those relative paths from the directory of the `.Rmd` file. – cookesd Feb 24 '21 at 17:03