51

setwd in an Rmd file in RStudio does not appear to change the directory in subsequent chunks. Is there a way to set the working directory for good?

Example:

```{r}
setwd("/tmp")
getwd()
```

```{r}
getwd()
```

Output:

setwd("/tmp")
getwd()
## [1] "/private/tmp"

getwd()
## [1] "/Users/me/src"

This is on Mac OS 10.8.5 using RStudio 0.97.551, R version 3.0.2 and knitr version 1.5.

I wish to set the directory once for all subsequent chunks.

user650654
  • 5,630
  • 3
  • 41
  • 44
  • 3
    I think this is a `knitr` issue. See https://github.com/yihui/knitr/issues/277#issuecomment-6528846 and see if it helps, though I [don't think Yihui is a fan](https://groups.google.com/forum/#!topic/knitr/knM0VWoexT0) of globally setting `setwd` – Tyler Rinker Nov 19 '13 at 00:07
  • 1
    Solution is [here](https://stackoverflow.com/questions/44538066/how-to-set-current-file-location-as-work-directory-in-r-markdown), use opts_knit rather than opts_chunk – Nate Breznau Jul 17 '19 at 09:29

2 Answers2

51

See Issue #277 and for further background, the package author's comments here

What you are looking for is the root.dir option in knitr::opts_knit.

The following will set the root directory for subsequent code chunks (but not this chunk):

```{r setup}
knitr::opts_knit$set(root.dir = '/tmp')
```

EDIT: RStudio 1.0.44

as of RStudio's latest release (Oct/Nov 2016), the following snippet is needed for knitr's render default:

```{r setup}
knitr::opts_knit$set(root.dir = '/tmp')
```

see Etienne's comment about versions below.

Yihui Xie
  • 28,913
  • 23
  • 193
  • 419
mnel
  • 113,303
  • 27
  • 265
  • 254
  • 6
    I needed to use `opts_knit` instead of `opts_chunk` – Etienne Low-Décarie Mar 06 '14 at 22:07
  • I also needed to use `opts_knit` -- may depend on whether one is using `rmarkdown::render` or `knitr::knit`, I was using the former (which is the default for RStudio's `knit HTML` button in 2016) – arvi1000 Apr 11 '16 at 21:04
  • 3
    This works in RStudio 1.0.143 for linux, but ONLY in the ```{r setup}...``` chunk. Just calling it ```{r initialization}...``` breaks it. – mightypile Apr 26 '17 at 11:14
  • 6
    This doesn't work for me: running this line followed by `getwd()` shows that it had no effect on the chunk working directory. Mac OS 10.11.6, R version 3.3.1, knitr version 1.17. – eric_kernfeld Feb 07 '18 at 19:35
  • Weird... I'm in RStudio Windows 1.1.456 and it seems to want `chunk` not `knit` – Hack-R Feb 24 '19 at 17:40
3

Here's what I've been using, and it seems to work well when using R Projects (.Rproj files):

knitr::opts_chunk$set(
    # This should allow Rmarkdown to locate the data
    root.dir = rprojroot::find_rstudio_root_file()
)
Matt Dancho
  • 6,840
  • 3
  • 35
  • 26
  • +1 I still had to explicitly set this via `setwd` though, so `setwd(rprojroot::find_rstudio_root_file())` worked. Any idea why it didnt work via your way through `knitr::opts_chunk$set`? – user63230 Apr 15 '21 at 10:51