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
Wrap Text Around Plots in Markdown
How to Conditionally Highlight Points in Ggplot2 Facet Plots - Mapping Color to Column
How to Use Empty Space Produced by Facet_Wrap
Output in R, Avoid Writing "[1]"
Find Out the Number of Days of a Month in R
How to Use Dplyr's Summarize and Which() to Lookup Min/Max Values
Merge Dataframes, Different Lengths
Combining S4 and S3 Methods in a Single Function
Edit Datatable in Shiny with Dropdown Selection for Factor Variables
Compute Monthly Averages from Daily Data
R: Ggplot Stacked Bar Chart with Counts on Y Axis But Percentage as Label
R Random Forest Error - Type of Predictors in New Data Do Not Match
Interactive Directory Input in Shiny App (R)