I would like to keep the base folder of my R Markdown project tree as uncluttered as possible and still use the Knit button in RStudio to see some results as an HTML output in the RStudio's preview window. However, every time I knit, an HTML file is created to the base folder along my .Rmd files.
My folder structure might look like this:
If I've understood correctly - and do please correct me if I'm wrong - it is not very straightforward to output the HTML files to an upstream folder (here:"results" folder) from an R Markdown file by pressing the Knit button, so I would be willing to:
So, if there is no easy way of directing the HTML files to the "results" folder, can I prevent the creation of HTML files altogether and only preview the results in the preview window?
I don't know of a way to attach this to the knit
button, but you could write a function that does this:
rmarkdown::render()
with the output_dir
argument set the way you want.You can attach this function to a keyboard shortcut in RStudio using these instructions.
Here's a simple version of the function:
knit2 <- function(filename = rstudioapi::getSourceEditorContext()$path,
output_dir = tempdir()) {
result <- rmarkdown::render(filename, output_dir = output_dir)
getOption("viewer")(result)
}
Simply call knit2()
, and the output will be written to tempdir()
, which means the preview will appear in the Viewer pane. If you want it to write to "results"
, call it as
knit2(output_dir = "results")
If that's not a subdirectory of tempdir()
, the preview will appear in an external browser.