9

I'm running into a strange problem. When I set my working directory from an R markdown chunk within an RStudio RMD file, by running the chunk, I am receiving the following error:

setwd('~/Users/Home/mypath/here')    

The working directory was changed to /Users/Home/mypath/here inside a notebook chunk. 
The working directory will be reset when the chunk is finished running. 
Use the knitr root.dir option in the setup chunk to change the the working directory for notebook chunks.

After I run this line of code from the chunk, and check getwd(), I get the following:

getwd()
"/Users/Home"

However, when I run setwd() from the console (literally copy and paste / run the code in the console), the working directory is changed.

I have never gotten this error using setwd() from a notebook chunk, and I setwd() from a notebook chunk on almost every RMD file I create. Why am I getting this error now, out of nowhere? It seems odd.

Canovice
  • 9,012
  • 22
  • 93
  • 211
  • 1
    Have a look here: https://stackoverflow.com/questions/30237310/setting-work-directory-in-knitr-using-opts-chunksetroot-dir-doesnt-wor – Phil Sep 01 '17 at 22:07

6 Answers6

10

In RStudio, in the Knit dropdown menu, select Knit directory, then Current Working Directory. Then rerun setwd(...). This fixed the problem for me.

Tommy
  • 124
  • 1
  • 3
9

its recommended to do it like this:

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
knitr::opts_knit$set(root.dir = "")
getwd()
```
mat
  • 129
  • 1
  • 11
  • 4
    didn't work for me, I've had this error re-occur several times and I find it wholly unclear why it happens – Gmichael Jun 09 '21 at 06:52
4

I found this code in the RStudio Community and it worked for me!

{r setup, include=FALSE, echo=FALSE}
require("knitr")
opts_knit$set(root.dir = "~/path/to/folder/")

Source is here.

Cananau Cristian
  • 436
  • 2
  • 6
  • 30
emr2
  • 1,436
  • 7
  • 23
0

I had to use the code posted below:

```{r setup, include=FALSE, echo=FALSE}
require("knitr")
opts_knit$set(root.dir = "~/path/to/folder/")
```

AND change my root directory manually by going to "Tools" -> "Global Options" etc.

This was the only way I finally fixed it after several days of trying everything. Delayed response, but hope it helps someone who needs it!

Carlos Luis Rivera
  • 3,108
  • 18
  • 45
Katie
  • 1
0

This worked for me

require("knitr")
opts_knit$set(root.dir = "~/path/to/folder/")
tjaas
  • 1
  • 1
  • While this code snippet may be the solution, including a detailed explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. – Shawn Hemelstrand Feb 03 '23 at 12:56
0

I just had this problem and selected "chunk output to console" under the settings wheel and it seemed to go away.