1

Context: I have a R project with disctinct folders for scripts, outputs and data. To match this logic, I would like to have .rmd files in the ./scripts/ folder while saving the .nb.html file in the ./outputs/ folder.

Question: how to make knit save the .nd.html file in the folder ./output/ when clicking the "Save" button in RStudio IDE?

I tried to change knitr options using knitr::opts_knit$set() without success. I know it is possible to use rmarkdown::render(input = "./scripts/test.Rmd", output_dir = "./outputs/") in a separate R script to do this but I am looking for a solution that does not require to make such separate R script.

This SO post is very close, and works for HTML outputs. However, with Notebooks it seems not to take into account the custom knit function into the YAML.

Here is the current folder-files tree:

C:.
|   testR.Rproj
|   
+---outputs
\---scripts
        test.Rmd

If I render the test.Rmd, I get the following:

C:.
|   testR.Rproj
|   
+---outputs
\---scripts
        test.nb.html
        test.Rmd

And the expected output is:

C:.
|   testR.Rproj
|   
+---outputs
|       test.nb.html
|       
\---scripts
        test.Rmd

Code to reproduce this structure the .Rmd file is empty, I do not know how to make the exact same output as File > New File > R Notebook:

library(usethis)
library(rmarkdown)
# set up the folder and files
usethis::create_project(path = paste0(getwd(),"/testR"), open = FALSE, rstudio = TRUE)
dir.create(paste0(getwd(),"/testR/outputs"))
dir.create(paste0(getwd(),"/testR/scripts"))
file.edit(paste0(getwd(),"/testR/scripts/test.Rmd"))
Paul
  • 2,850
  • 1
  • 12
  • 37

1 Answers1

1

You can try the following, in the yaml header, you can pass a function to knit parameter:

---
title: "Some Report"
knit: (function(input, ...) {rmarkdown::render(input, output_file="path/to/output/location/filename.html")})
output: html_document
---

You can read more here. Note although, in the link it is mentioned you can pass a multiline function, but I have had trouble with passing multiline function. Passing the function as a single line works. Since you are passing a function, you can parametrize (do more things) it further, for example see here

monte
  • 1,482
  • 1
  • 10
  • 26
  • What a nice trick! It works very well with `.html` documents but it seems that `html_notebooks` are not supported. However, by using the `code_folding` YAML parameter with `html_document` instead of `html_notebook` it is possible to get very close to the expected output! – Paul May 12 '22 at 14:05
  • This YALM works: `knit: (function(input, ...) {rmarkdown::render(input, output_dir=paste0(rprojroot::find_rstudio_root_file(), "/outputs/"))}) output: html_document: code_folding: hide` – Paul May 12 '22 at 14:06
  • This one does not: `knit: (function(input, ...) {rmarkdown::render(input, output_dir=paste0(rprojroot::find_rstudio_root_file(), "/outputs/"))}) output: html_notebook` – Paul May 12 '22 at 14:07