Ok, now this works and it's fully reproducible. Assume this project directory:
-
project\
project.Rproj
-
code\
render_report.r
myreport.Rmd
output\
Files as follows:
render_report.r file (note the use of file.path() to avoid any dependency on the operative system
)
library(rmarkdown)
code_dir <- "code"
report_filename <- "myreport.Rmd"
report_filename <- file.path(code_dir, report_filename)
output_dir <- "output"
output <- file.path("..",output_dir)
render(report_filename, output_dir = output_dir, params = list(output_dir = output))
myreport.Rmd file
---
title: "myreport"
author: "Andrea Panizza"
date: "`r Sys.Date()`"
output: html_document
params:
output_dir: "../foobar"
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(readr)
# Set output directory
data_dir <- "../data"
output_dir <- params$output_dir
```
## Complex computations
```{r mean, echo=FALSE}
average <- mean(seq(1,10))
results <- data.frame(average = average)
```
## Save results
```{r write_data}
output_filename <- ("results.csv")
output_path <- file.path(output_dir, output_filename)
write_csv(results, output_path)
```
@Frank note that the default value for params$output_dir is now a non-existent directory! So if parameters substitution didn't work, then I would get an error.
After running render_report.r, I get:
-
project\
project.Rproj
-
code\
render_report.r
myreport.Rmd
-
output\
myreport.html
results.csv
Phew! It was harder than I thought.
@mara you were right! There's no way to do this with the "Knit" button. However, this solution at least doesn't require me to leave RStudio. Actually, the "Knit" button could place myreport.html in the project\ dir, which is also fine (better than in the code dir, IMO). Still, I have an output dir, why not use it and keep everything nice and tidy
?