Setting Work Directory in Knitr Using Opts_Chunk$Set(Root.Dir = ...) Doesn't Work

Setting work directory in knitr using opts_chunk$set(root.dir = ...) doesn't work

It is knitr::opts_knit instead of knitr::opts_chunk.

Cant set working directory in R notebook chunk, strange error

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

In RStudio/RMarkdown, how to setwd?

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.

Working with knitr using subdirectories

Try this. It assumes you have the 4 folders you listed inside the working directory project. It also assumes you have a .csv file called myData.csv in data.

When you knit the file, the plot will be saved in figures. At the end, the code looks for html files in code and moves them to documents. There's probably a better way to do this.

```{r setup}
library(knitr)
opts_knit$set(root.dir=normalizePath('../'))
opts_chunk$set(fig.path = "../figures/", dev='pdf') # corrected path and added dev
```

```{r import}
dat <- read.csv("data/myData.csv")
```

```{r plot}
# pdf(file="figures/test.pdf") # I do this in setup instead
plot(dat)
# dev.off()
```

```{r move}
files <- list.files("code/")
index <- grep("html", files)
file.rename(file.path("code", files[index]),
file.path("documents", files[index]))
```


Related Topics



Leave a reply



Submit