Home > OS >  Is it possible to knit an R Markdown file only to a preview window/pane in RStudio without saving an
Is it possible to knit an R Markdown file only to a preview window/pane in RStudio without saving an

Time:09-18

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:

enter image description here

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:

  1. prevent the creation of HTML files altogether,
  2. still see the results in an HTML format in RStudio's preview window, and
  3. only when I'm really willing to save an HTML file, save (export) such a file and (manually) transfer it to the results folder.

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?

CodePudding user response:

I don't know of a way to attach this to the knit button, but you could write a function that does this:

  • get the current file open in the edit pane. This answer gives details on that.
  • run 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.

  • Related