Setting working directory in RMarkdown

Can anyone help me as to why this code isn't working to set the directory? In the console you can see it doesn't set the whole path as the directory. Everything is spelled and (un)capitalized correctly.

1 Like

You are setting the root directory where the file is going to be knitted, not your current working directory, they are different, the document gets knitted on a separate clean R session.

1 Like

So to set the working directory I should just do that in the console?

Yes, but manually setting the working directory is not considered a good practice, it's better to work inside an RStudio project which sets the working directory automatically.

1 Like

I think there might be multiple issues here.

For the Rmd file, the result of getwd() in the setup chunk may be surprising since root.dir was changed. However, the working directory of a code chunk is set before any of the code inside it is executed. Thus the change to root.dir won't be evident until later chunks are run. You can run the following Rmd file to confirm that the working directory is changed for the rest of the document.

---
output: word_document
---

```{r setup}
knitr::opts_knit$set(root.dir = "C:/Users/Laura/Documents/RStudio/dsc520")
getwd()
```

```{r check-wd}
getwd()
```

For the R console, you have to use setwd() to change the working directory. knitr::opts_knit() has no effect outside of an Rmd file.

Lastly, if you want to make it easier for others to run your code on their machine, you don't want to use absolute paths like C:/Users/Laura/Documents/RStudio/dsc520. If the Rmd file is saved in assignments/, but you want it to be executed from the root of the project, you can use the relative path .., i.e. knitr::opts_knit$set(root.dir = ".."). Another useful tool for dealing with working directories is the package here.

4 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.