3.2 Render Rmd

When you click the Knit button (⇧⌘K) in RStudio, generally two processes happen:

  1. The .Rmd file is fed to knitr, which executes all of the R code chunks and creates a new markdown (.md) document which includes the R code and its output.
  2. The .md file is then processed by pandoc which is responsible for creating the finished format, e.g., HTML, PDF, MS_Word.
    • .md files can be directly converted to html, but
    • .md to pdf is time-consuming. It first generates .tex, then call the LaTeX engine to convert to pdf.

There is one function that can do the processes mentioned above: rmarkdown::render.

3.2.1 Render a single document

rmarkdown::render(input, output_format = NULL, output_file = NULL, output_dir = NULL, output_options = NULL, output_yaml = NULL)

Arguments Definition
output_format - "all" will render all formats define within the file
- Name of a format, e.g., html_document, will render to that single format
- An output format object, e.g., html_document(toc = TRUE, toc_depth = 2, includes = includes(before_body = "header.htm")), where you can pass on the argument
output_options - List of output options that can override the options specified in metadata (e.g could be used to force self_contained or mathjax = "local").
- Note that this is only valid when the output format is read from metadata (i.e. not a custom format object passed to output_format).
- output_options cannot work together with xxx_document().
output_yaml Paths to YAML files specifying output formats and their configurations. The first existing one is used. If none are found, then the function searches YAML files specified to the output_yaml top-level parameter in the YAML front matter, _output.yml or _output.yaml, and then uses the first existing one.

Use examples of render, using output format objects

rmarkdown::render("0208-Rmd-GHpage.Rmd", 
    bookdown::pdf_document2(
        latex_engine = "xelatex",
        # template = "latex/template.tex",
        includes = rmarkdown::includes(
            in_header = "latex/preamble.tex",
      before_body = "latex/before_body.tex")
        ))

# This does NOT work as `output_options` is only valid when the format is not an output format object "xxx_document()"
rmarkdown::render("0208-Rmd-GHpage.Rmd", 
    bookdown::pdf_document2(
        latex_engine = "xelatex",
        # template = "latex/template.tex"), 
        output_options = list(
            includes = rmarkdown::includes(
        in_header = "latex/preamble.tex",
        before_body = "latex/before_body.tex")
        ))

# render to html
rmarkdown::render("0304-Quarto.Rmd",  
    bookdown::html_document2(
        includes = rmarkdown::includes(
            in_header = "head.html",
            before_body = "scripts.html")
        ))

Note that sometimes the bookdown cross references in Rmd are not rendered when using the Knit button. The rendered html shows Fig. \@ref(fig:ar-res) (without the backslash). In this case, using rmarkdown::render() with output_format = bookdown::html_document2() might help.


You can have more than one output formats for your Rmd. For example, you want both the html and pdf output.

When you render the Rmd with rmarkdown::render(), it will use the first output format you specify in the YAML metadata (if it is missing, the default is html_document).

If you do not want to use the first one, you can specify the one you want in the second argument, e.g., for an Rmd document input.Rmd with the metadata:

output:
  html_document:
    toc: true
  pdf_document:
    keep_tex: true

You can render it to PDF via:

# Render to pdf
rmarkdown::render('input.Rmd', 'pdf_document')

# Render multiple formats
render("input.Rmd", c("html_document", "pdf_document"))

# Render all formats defined
rmarkdown::render('input.Rmd', 'all')
  • RStudio calls the function rmarkdown::render() to render the document in a new R session.

    RStudio does this to ensure reproducibility.


Fast rendering within the current global environment

rmarkdown::render(active_document_path, envir=.GlobalEnv)

What this does:

  • Uses .GlobalEnv to access all objects already loaded in your workspace
  • Faster rendering since it skips the overhead of starting a new R session
  • All variables, functions, and loaded packages from your current session are available

Caveats:

  • ⚠️ Less reproducible - document depends on current session state
  • ⚠️ Potential conflicts - objects in current session might interfere with document

3.2.2 Render multiple documents as a website

rmarkdown::render_site(input = ".", output_format = "all") Render all of the R Markdown documents within a directory as a website.

There are two requirements for a directory to be rendered as a website:

  • It must contain either an index.Rmd or index.md file.
  • It must contain a site configuration file
    • R Markdown websites: _site.yml.
    • Bookdown websites: output.yml (output formats) and _bookdown.yml (book-specific metadata).

Note that the “Knit” button in RStudio uses rmarkdown::render_site to knit the file in presence of an index.Rmd file in the working directory.

Argument Definition
input Website directory (or the name of a file within the directory).
output_format R Markdown format to convert to (defaults to “all”).
encoding Ignored. The encoding is always assumed to be UTF-8.

What will happen:

  • All output and supporting files are copied to a “_site” subdirectory of the website directory.

    This is configurable with output_dir in _site.yml.

    output_dir: indicates which directory to copy site content into.

Refer to Rmd GitHub Pages for more details about rendering websites.

Use example:

# render the entire site, if input_file is not specified
# render all output formats defined in `_output.yml`
rmarkdown::render_site()

# render the entire site for gitbook format only
rmarkdown::render_site(output_format = "bookdown::gitbook")

# render a single file only
rmarkdown::render_site("about.Rmd")

rmarkdown::render_site("onefile.Rmd") is useful when you want to render a single file in the site, e.g., about.Rmd or index.Rmd, without rendering the entire site. It is useful for testing changes to a single file without having to render the entire site.

  • It uses all settings in _output.yml to render the file, such as the output format, output directory, and other options.
  • It is faster than rendering the entire site because it only processes the specified file and its dependencies, rather than all files in the site.
  • You can view the updates in the server http://127.0.0.1:port/. If the server has live reloading enabled, it automatically detects changes to the file and updates the output in real-time. Then you don’t need to restart or refresh the server to see the changes.