Movatterモバイル変換


[0]ホーム

URL:


Type:Package
Title:Dynamic Documents for R
Version:2.30
Description:Convert R Markdown documents into a variety of formats.
License:GPL-3
URL:https://github.com/rstudio/rmarkdown,https://pkgs.rstudio.com/rmarkdown/
BugReports:https://github.com/rstudio/rmarkdown/issues
Depends:R (≥ 3.0)
Imports:bslib (≥ 0.2.5.1), evaluate (≥ 0.13), fontawesome (≥0.5.0), htmltools (≥ 0.5.1), jquerylib, jsonlite, knitr (≥1.43), methods, tinytex (≥ 0.31), tools, utils, xfun (≥0.36), yaml (≥ 2.1.19)
Suggests:digest, dygraphs, fs, rsconnect, downlit (≥ 0.4.0), katex(≥ 1.4.0), sass (≥ 0.4.0), shiny (≥ 1.6.0), testthat (≥3.0.3), tibble, vctrs, cleanrmd, withr (≥ 2.4.2), xml2
VignetteBuilder:knitr
Config/Needs/website:rstudio/quillt, pkgdown
Config/testthat/edition:3
Encoding:UTF-8
RoxygenNote:7.3.2
SystemRequirements:pandoc (>= 1.14) - http://pandoc.org
NeedsCompilation:no
Packaged:2025-09-25 03:25:30 UTC; yihui
Author:JJ Allaire [aut], Yihui XieORCID iD [aut, cre], Christophe DervieuxORCID iD [aut], Jonathan McPherson [aut], Javier Luraschi [aut], Kevin Ushey [aut], Aron Atkins [aut], Hadley Wickham [aut], Joe Cheng [aut], Winston Chang [aut], Richard IannoneORCID iD [aut], Andrew DunningORCID iD [ctb], Atsushi YasumotoORCID iD [ctb, cph] (cph: Number sections Lua filter), Barret Schloerke [ctb], Carson SievertORCID iD [ctb], Devon RyanORCID iD [ctb], Frederik AustORCID iD [ctb], Jeff Allen [ctb], JooYoung SeoORCID iD [ctb], Malcolm Barrett [ctb], Rob Hyndman [ctb], Romain Lesur [ctb], Roy Storey [ctb], Ruben Arslan [ctb], Sergio Oller [ctb], Posit Software, PBC [cph, fnd], jQuery UI contributors [ctb, cph] (jQuery UI library; authors listed in inst/rmd/h/jqueryui/AUTHORS.txt), Mark Otto [ctb] (Bootstrap library), Jacob Thornton [ctb] (Bootstrap library), Bootstrap contributors [ctb] (Bootstrap library), Twitter, Inc [cph] (Bootstrap library), Alexander Farkas [ctb, cph] (html5shiv library), Scott Jehl [ctb, cph] (Respond.js library), Ivan Sagalaev [ctb, cph] (highlight.js library), Greg Franko [ctb, cph] (tocify library), John MacFarlane [ctb, cph] (Pandoc templates), Google, Inc. [ctb, cph] (ioslides library), Dave Raggett [ctb] (slidy library), W3C [cph] (slidy library), Dave Gandy [ctb, cph] (Font-Awesome), Ben Sperry [ctb] (Ionicons), Drifty [cph] (Ionicons), Aidan Lister [ctb, cph] (jQuery StickyTabs), Benct Philip Jonsson [ctb, cph] (pagebreak Lua filter), Albert Krewinkel [ctb, cph] (pagebreak Lua filter)
Maintainer:Yihui Xie <xie@yihui.name>
Repository:CRAN
Date/Publication:2025-09-28 11:30:02 UTC

R Markdown Document Conversion

Description

Convert R Markdown documents into a variety of formats including HTML,MS Word, PDF, and Beamer.

Details

Thermarkdown package includes high level functions forconverting to a variety of formats. For example:

render("input.Rmd", html_document())render("input.Rmd", pdf_document())

You can also specify a plain markdown file in which case knitting will bebypassed:

render("input.md", html_document())

Additional options can be specified along with the output format:

render("input.Rmd", html_document(toc = TRUE))render("input.Rmd", pdf_document(latex_engine = "lualatex"))render("input.Rmd", beamer_presentation(incremental = TRUE))

You can also include arbitrary pandoc command line arguments along with theother options:

render("input.Rmd", pdf_document(toc = TRUE, pandoc_args = "--listings"))

Author(s)

Maintainer: Yihui Xiexie@yihui.name (ORCID)

Authors:

Other contributors:

See Also

render,html_document,pdf_document,word_document,beamer_presentation


Determine all output formats for an R Markdown document

Description

Read the YAML metadata (and any common output YAML file) for thedocument and return the output formats that will be generated bya call torender.

Usage

all_output_formats(input, output_yaml = NULL)

Arguments

input

Input file (Rmd or plain markdown)

output_yaml

Paths to YAML files specifying output formats and theirconfigurations. The first existing one is used. If none are found, thenthe function searches YAML files specified to theoutput_yaml top-levelparameter in the YAML front matter, _output.yml or _output.yaml, and then usesthe first existing one.

Details

This function is useful for front-end tools that require additionalknowledge of the output to be produced byrender (e.g. tocustomize the preview experience).

Value

A character vector with the names of all output formats.


List available R Markdown template in a package

Description

List the available template by name that can be used withdraft() to createa new document for R Markdown from a package.

Usage

available_templates(package = "rmarkdown", full_path = FALSE)

Arguments

package

Package to list template from. Default tormarkdown

full_path

Set toTRUE to get the full path to the available templates

Value

A character vector of templates name to use withindraft(). Iffull_path = TRUE, it returns the full path to the templates.

Examples

# List rmarkdown templates & create a draftavailable_templates()# List rticles templatesavailable_templates("rticles")

Convert to a Beamer presentation

Description

Format for converting from R Markdown to a Beamer presentation.

Usage

beamer_presentation(  toc = FALSE,  slide_level = NULL,  number_sections = FALSE,  incremental = FALSE,  fig_width = 10,  fig_height = 7,  fig_crop = "auto",  fig_caption = TRUE,  dev = "pdf",  df_print = "default",  theme = "default",  colortheme = "default",  fonttheme = "default",  highlight = "default",  template = "default",  keep_tex = FALSE,  keep_md = FALSE,  latex_engine = "pdflatex",  citation_package = c("default", "natbib", "biblatex"),  self_contained = TRUE,  includes = NULL,  md_extensions = NULL,  pandoc_args = NULL,  extra_dependencies = NULL)

Arguments

toc

TRUE to include a table of contents in the output (onlylevel 1 headers will be included in the table of contents).

slide_level

The heading level which defines individual slides. Bydefault this is the highest header level in the hierarchy that is followedimmediately by content, and not another header, somewhere in the document.This default can be overridden by specifying an explicitslide_level.

number_sections

TRUE to number section headings

incremental

TRUE to render slide bullets incrementally. Notethat if you want to reverse the default incremental behavior for anindividual bullet you can precede it with>. For example:⁠> - Bullet Text⁠. See more inPandoc's Manual

fig_width

Default width (in inches) for figures

fig_height

Default height (in inches) for figures

fig_crop

Whether to crop PDF figures with the commandpdfcrop. This requires the toolspdfcrop andghostscript to be installed. By default,fig_crop = TRUEif these two tools are available.

fig_caption

TRUE to render figures with captions

dev

Graphics device to use for figure output (defaults to pdf)

df_print

Method to be used for printing data frames. Valid valuesinclude "default", "kable", "tibble", and "paged". The "default" methoduses a corresponding S3 method ofprint, typicallyprint.data.frame. The "kable" method uses theknitr::kable function. The "tibble" method usesthetibble package to print a summary of the data frame. The "paged"method creates a paginated HTML table (note that this method is only validfor formats that produce HTML). In addition to the named methods you canalso pass an arbitrary function to be used for printing data frames. Youcan disable thedf_print behavior entirely by setting the optionrmarkdown.df_print toFALSE. SeeDataframe printing section in bookdown book for examples.

theme

Beamer theme (e.g. "AnnArbor").

colortheme

Beamer color theme (e.g. "dolphin").

fonttheme

Beamer font theme (e.g. "structurebold").

highlight

Syntax highlighting style passed to Pandoc.

Supported built-in styles include "default", "tango", "pygments", "kate","monochrome", "espresso", "zenburn", "haddock", and "breezedark".

Two custom styles are also included, "arrow", an accessible color scheme,and "rstudio", which mimics the default IDE theme. Alternatively, supply apath to a ‘⁠.theme⁠’ file to usea custom Pandocstyle. Note that custom theme requires Pandoc 2.0+.

PassNULL to prevent syntax highlighting.

template

Pandoc template to use for rendering. Pass "default" to usethe rmarkdown package default template; passNULL to use pandoc'sbuilt-in template; pass a path to use a custom template that you'vecreated. See the documentation onpandoc online documentation fordetails on creating custom templates.

keep_tex

Keep the intermediate tex file used in the conversion to PDF.Note that this argument does not control whether to keep the auxiliaryfiles (e.g., ‘.aux’) generated by LaTeX when compiling ‘.tex’ to‘.pdf’. To keep these files, you may setoptions(tinytex.clean =FALSE).

keep_md

Keep the markdown file generated by knitting.

latex_engine

LaTeX engine for producing PDF output. Options are"pdflatex", "lualatex", "xelatex" and "tectonic".

citation_package

The LaTeX package to process citations,natbiborbiblatex. Usedefault if neither package is to be used,which means citations will be processed via the commandpandoc-citeproc.

self_contained

Whether to generate a full LaTeX document (TRUE)or just the body of a LaTeX document (FALSE). Note the LaTeXdocument is an intermediate file unlesskeep_tex = TRUE.

includes

Named list of additional content to include within thedocument (typically created using theincludes function).

md_extensions

Markdown extensions to be added or removed from thedefault definition of R Markdown. See thermarkdown_format foradditional details.

pandoc_args

Additional command line options to pass to pandoc

extra_dependencies

A LaTeX dependencylatex_dependency(), alist of LaTeX dependencies, a character vector of LaTeX package names (e.g.c("framed", "hyperref")), or a named list of LaTeX package optionswith the names being package names (e.g.list(hyperef =c("unicode=true", "breaklinks=true"), lmodern = NULL)). It can be used toadd custom LaTeX packages to the .tex header.

Details

See theonline documentationfor additional details on using thebeamer_presentation format.

Creating Beamer output from R Markdown requires that LaTeX be installed.

R Markdown documents can have optional metadata that is used to generate adocument header that includes the title, author, and date. For more detailssee the documentation on R Markdownmetadata.

R Markdown documents also support citations. You can find more information onthe markdown syntax for citations in theBibliographies and Citationsarticle in the online documentation.

Value

R Markdown output format to pass torender()

Examples

## Not run: library(rmarkdown)# simple invocationrender("pres.Rmd", beamer_presentation())# specify an option for incremental renderingrender("pres.Rmd", beamer_presentation(incremental = TRUE))## End(Not run)

Compiling R scripts to a notebook

Description

R Markdown can also compile R scripts to a notebook which includescommentary, source code, and script output. Notebooks can be compiled to anyoutput format including HTML, PDF, and MS Word.

Overview

To compile a notebook from an R script you simply pass the script torender. For example:

rmarkdown::render("analysis.R")rmarkdown::render("analysis.R", "pdf_document")

The first call torender creates an HTML document, whereasthe second creates a PDF document.

By default the name of the script, username, and current date and time areincluded in the header of the generated notebook. You can override thisdefault behavior by including explicit metadata in a specially formatted Rcomment:

#' ---#' title: "Crop Analysis Q3 2013"#' author: "John Smith"#' date: "May 3rd, 2014"#' ---

Including Markdown

Note that the R comment used above to add a title, author, and dateincludes a single-quote as a special prefix character. This is aroxygen2 style comment, and it's actually possible to include manysuch comments in an R script, all of which will be converted to markdowncontent within the generated notebook. For example:

#' A script comment that includes **markdown** formatting.

Rather than displaying as an R comment in the compiled notebook anyroxygen2 style comment will be treated as markdown and renderedaccordingly.

knitr Spin

Including markdown within R comments is possible becauserendercalls theknitr spin function to convert the Rscript to an Rmd file. Thespin function also enables you to addknitrchunk options with another special comment prefix (#+).

Here's an example of a script that uses the various features ofspin:

https://github.com/yihui/knitr/blob/master/inst/examples/knitr-spin.R

For more details onknitr::spin see the following documentation:

https://yihui.org/knitr/demo/stitch/


Convert to a ConTeXt document

Description

Format for converting from R Markdown to PDF using ConTeXt.

Usage

context_document(  toc = FALSE,  toc_depth = 2,  number_sections = FALSE,  fig_width = 6.5,  fig_height = 4.5,  fig_crop = "auto",  fig_caption = TRUE,  dev = "pdf",  df_print = "default",  template = NULL,  keep_tex = FALSE,  keep_md = FALSE,  citation_package = c("default", "natbib", "biblatex"),  includes = NULL,  md_extensions = NULL,  output_extensions = NULL,  pandoc_args = NULL,  context_path = NULL,  context_args = NULL,  ext = c(".pdf", ".tex"))

Arguments

toc

TRUE to include a table of contents in the output

toc_depth

Depth of headers to include in table of contents

number_sections

TRUE to number section headings

fig_width

Default width (in inches) for figures

fig_height

Default height (in inches) for figures

fig_crop

Whether to crop PDF figures with the commandpdfcrop. This requires the toolspdfcrop andghostscript to be installed. By default,fig_crop = TRUEif these two tools are available.

fig_caption

TRUE to render figures with captions

dev

Graphics device to use for figure output (defaults to pdf)

df_print

Method to be used for printing data frames. Valid valuesinclude "default", "kable", "tibble", and "paged". The "default" methoduses a corresponding S3 method ofprint, typicallyprint.data.frame. The "kable" method uses theknitr::kable function. The "tibble" method usesthetibble package to print a summary of the data frame. The "paged"method creates a paginated HTML table (note that this method is only validfor formats that produce HTML). In addition to the named methods you canalso pass an arbitrary function to be used for printing data frames. Youcan disable thedf_print behavior entirely by setting the optionrmarkdown.df_print toFALSE. SeeDataframe printing section in bookdown book for examples.

template

Pandoc template to use for rendering. Pass "default" to usethe rmarkdown package default template; passNULL to use pandoc'sbuilt-in template; pass a path to use a custom template that you'vecreated. See the documentation onpandoc online documentation fordetails on creating custom templates.

keep_tex

Keep the intermediate tex file used in the conversion to PDF.Note that this argument does not control whether to keep the auxiliaryfiles (e.g., ‘.aux’) generated by LaTeX when compiling ‘.tex’ to‘.pdf’. To keep these files, you may setoptions(tinytex.clean =FALSE).

keep_md

Keep the markdown file generated by knitting.

citation_package

The LaTeX package to process citations,natbiborbiblatex. Usedefault if neither package is to be used,which means citations will be processed via the commandpandoc-citeproc.

includes

Named list of additional content to include within thedocument (typically created using theincludes function).

md_extensions

Markdown extensions to be added or removed from thedefault definition of R Markdown. See thermarkdown_format foradditional details.

output_extensions

Pandoc extensions to be added or removed from theoutput format, e.g.,"-smart" means the output format will belatex-smart.

pandoc_args

Additional command line options to pass to pandoc

context_path

Path of the ConTeXt executable. If not provided, ConTeXthas to be available from thePATH environment variable.

context_args

Command line arguments passed to ConTeXt.

ext

Format of the output document (defaults to ".pdf").

Details

ConTeXt needs to be installed, e.g., you can install it withtinytex::tlmgr_install("context").

R Markdown documents can have optional metadata that is used to generate adocument header that includes the title, author, and date. For more detailssee the documentation on R Markdownmetadata.

R Markdown documents also support citations. You can find more information onthe markdown syntax for citations in theBibliographiesand Citations article in the online documentation.

Value

R Markdown output format to pass torender.

Examples

## Not run: library(rmarkdown)# simple invocationrender("input.Rmd", context_document())## End(Not run)

Convert a Jupyter/IPython notebook to an R Markdown document

Description

Read a Jupyter/IPython notebook file (‘.ipynb’) viajsonlite::fromJSON(), convert its code cells to R Markdown codechunks, preserve Markdown cells, and write out the results to an Rmd file.

Usage

convert_ipynb(input, output = xfun::with_ext(input, "Rmd"))

Arguments

input

Path to the input ‘.ipynb’ file.

output

The output file path.

Details

This simple converter may have some rough edges, depending on how manyIPython-specific features are used in a notebook. For example, line magicsare not automatically converted (warnings will be issued if line magics aredetected), but you may consider using or writing R functions to replace themin R Markdown (e.g., the%load magic may be replaced byreticulate::source_python()). Cell magics will be converted to codechunks with the (knitr) language engine names being the magic names.For example, the cell magic%%js is converted to⁠```{js}⁠in R Markdown. This does not always work because not all IPython cell magicshave their counterparts inknitr's language engines, but common cellmagics like%%bash,%%sh,%%js,%%perl,%%python, and%%ruby should work.

Value

The output file path (invisibly).

Examples

# this is not a real ipynb file, but illustrates what convert_ipynb() doesnb_data <- list(  cells = list(    list(cell_type = 'markdown', source = 'Hi **Markdown**!'),    list(cell_type = 'code', source = 'print("Hi R Markdown!")')  ),  metadata = list(    kernelspec = list(language = 'python')  ))nb_file = tempfile(fileext = '.ipynb')jsonlite::write_json(nb_data, nb_file, auto_unbox = TRUE, pretty = TRUE)xfun::file_string(nb_file)  # show file content# convert to R Markdownnb_rmd = rmarkdown:::convert_ipynb(nb_file)xfun::file_string(nb_rmd)

Determine the default output format for an R Markdown document

Description

Read the YAML metadata (and any common output YAML file) for thedocument and return the output format that will be generated bya call torender.

Usage

default_output_format(input, output_yaml = NULL)

Arguments

input

Input file (Rmd or plain markdown)

output_yaml

Paths to YAML files specifying output formats and theirconfigurations. The first existing one is used. If none are found, thenthe function searches YAML files specified to theoutput_yaml top-levelparameter in the YAML front matter, _output.yml or _output.yaml, and then usesthe first existing one.

Details

This function is useful for front-end tools that require additionalknowledge of the output to be produced byrender (e.g. tocustomize the preview experience).

Value

A named list with aname value containing the formatname and anoptions value that is a list containing all the optionsfor the format and their values. An option's default value will be returnedif the option isn't set explicitly in the document.


Create a new document based on a template

Description

Create (and optionally edit) a draft of an R Markdown document based on atemplate.

Usage

draft(file, template, package = NULL, create_dir = "default", edit = TRUE)

Arguments

file

File name for the draft

template

Template to use as the basis for the draft. This is eitherthe full path to a template directory or the name of a template directorywithin thermarkdown/templates directory of a package.

package

(Optional) Name of package where the template is located.

create_dir

TRUE to create a new directory for the document(the "default" setting leaves this behavior up to the creator of thetemplate).

edit

TRUE to edit the template immediately

Details

Thedraft function creates new R Markdown documents based ontemplates that are either located on the filesystem or within an R package.The template and its supporting files will be copied to the locationspecified byfile.

Value

The file name of the new document (invisibly).

Note

An R Markdown template consists of a directory that contains adescription of the template, a skeleton Rmd file used as the basis for newdocuments, and optionally additional supporting files that are providedalong with the skeleton (e.g. a logo graphic).

If the template directory is contained within a package then it should belocated atinst/rmarkdown/templates. For example, a package namedpubtools that wanted to provide a template namedquarterly_report would need to provide the following files withinthepubtools/inst/rmarkdown/templates directory:

quarterly_report/template.yaml
quarterly_report/skeleton/skeleton.Rmd

Thetemplate.yaml file should include aname field. If youwant to ensure that a new directory is always created for a given template,then you can add thecreate_dir field to thetemplate.yamlfile. For example:

create_dir: true

Theskeleton/skeleton.Rmd file should include the initial contentsyou want for files created from this template. Additional files can beadded to theskeleton directory, for example:

skeleton/logo.png

These files will automatically be copied to the directory containing thenew R Markdown draft.

Examples

## Not run: rmarkdown::draft("Q4Report.Rmd",                 template="/opt/rmd/templates/quarterly_report")rmarkdown::draft("Q4Report.Rmd",                 template="quarterly_report", package="pubtools")## End(Not run)

Find External Resource References

Description

Given an R Markdown document or HTML file, attempt to determine the set ofadditional files needed in order to render and display the document.

Usage

find_external_resources(input_file, encoding = "UTF-8")

Arguments

input_file

path to the R Markdown document or HTML file to process

encoding

Ignored. The encoding is always assumed to be UTF-8.

Details

This routine applies heuristics in order to scan a document forpossible resource references.

In R Markdown documents, it looks for references to files implicitlyreferenced in Markdown (e.g.![alt](img.png)), in the document'sYAML header, in raw HTML chunks, and as quoted strings in R code chunks(e.g.read.csv("data.csv")).

Resources specified explicitly in the YAML header for R Markdowndocuments are also returned. To specify resources in YAML, use theresource_files key:

---title: My Documentauthor: My Nameresource_files:  - data/mydata.csv  - images/figure.png---

Each item in theresource_files list can refer to:

  1. A single file, such asimages/figure.png, or

  2. A directory, such asresources/data, in which case all of thedirectory's content will be recursively included, or

  3. A wildcard pattern, such asdata/*.csv, in which case all ofthe files matching the pattern will be included. No recursion is done inthis case.

In HTML files (and raw HTML chunks in R Markdown documents), this routinesearches for resources specified in common tag attributes, such as<img src="...">,<link href="...">, etc.

In all cases, only resources that exist on disk and are contained in thedocument's directory (or a child thereof) are returned.

Value

A data frame with the following columns:

path

The relative path from the document to the resource

explicit

Whether the resource was specified explicitly(TRUE) or discovered implicitly (FALSE)

web

Whether the resource is needed to display a Web page renderedfrom the document


Find thepandoc executable

Description

Searches for thepandoc executable in a few places and use thehighest version found, unless a specific version is requested.

Usage

find_pandoc(cache = TRUE, dir = NULL, version = NULL)

Arguments

cache

Whether to search forpandoc again if a Pandocdirectory containing thepandoc executable of the expectedversion (if provided) has been found previously. Search again ifcache = FALSE.

dir

A character vector of potential directory paths under whichpandoc may be found. If not provided, this function searches forpandoc from the environment variableRSTUDIO_PANDOC (theRStudio IDE will set this variable to the directory of Pandoc bundled withthe IDE), the environment variablePATH, and the directory‘~/opt/pandoc/’.

version

The version of Pandoc to look for (e.g.,"2.9.2.1"). Ifnot provided, this function searches for the highest version under thepotential directories.

Value

A list containing the directory and version of Pandoc (if found).

Note

Usually you do not need to install Pandoc if you use the RStudio IDE,because the IDE has bundled a version of Pandoc. If you have installed aversion of Pandoc by yourself and want to use this version instead, you mayuse thedir argument of this function.

Examples

rmarkdown::find_pandoc()rmarkdown::find_pandoc(dir = '~/Downloads/Pandoc')rmarkdown::find_pandoc(version = '2.7.3')

Convert to GitHub Flavored Markdown

Description

Format for converting from R Markdown to GitHub Flavored Markdown.

Usage

github_document(  toc = FALSE,  toc_depth = 3,  number_sections = FALSE,  math_method = "default",  preserve_yaml = FALSE,  fig_width = 7,  fig_height = 5,  dev = "png",  df_print = "default",  includes = NULL,  md_extensions = NULL,  hard_line_breaks = TRUE,  pandoc_args = NULL,  html_preview = TRUE,  keep_html = FALSE)

Arguments

toc

TRUE to include a table of contents in the output

toc_depth

Depth of headers to include in table of contents

number_sections

TRUE to number section headings

math_method

"default" means thatnative Github supportfor math notations using Mathjax syntax will be used. Other possible valueis"webtex" where equation will be rendered to an image in the resultingMarkdown. Seehtml_document() for option to change webtex URL. Setmath_methodtoNULL to opt-out any math treatment.

preserve_yaml

Preserve YAML front matter in final document.

fig_width

Default width (in inches) for figures

fig_height

Default height (in inches) for figures

dev

Graphics device to use for figure output (defaults to png)

df_print

Method to be used for printing data frames. Valid valuesinclude "default", "kable", "tibble", and "paged". The "default" methoduses a corresponding S3 method ofprint, typicallyprint.data.frame. The "kable" method uses theknitr::kable function. The "tibble" method usesthetibble package to print a summary of the data frame. The "paged"method creates a paginated HTML table (note that this method is only validfor formats that produce HTML). In addition to the named methods you canalso pass an arbitrary function to be used for printing data frames. Youcan disable thedf_print behavior entirely by setting the optionrmarkdown.df_print toFALSE. SeeDataframe printing section in bookdown book for examples.

includes

Named list of additional content to include within thedocument (typically created using theincludes function).

md_extensions

Markdown extensions to be added or removed from thedefault definition of R Markdown. See thermarkdown_format foradditional details.

hard_line_breaks

TRUE to generate markdown that uses a simplenewline to represent a line break (as opposed to two-spaces and a newline).

pandoc_args

Additional command line options to pass to pandoc

html_preview

TRUE to also generate an HTML file for the purpose oflocally previewing what the document will look like on GitHub.

keep_html

TRUE to keep the preview HTML file in the workingdirectory. Default isFALSE.

Details

See theonline documentation for additional details on using thegithub_document()format.

Value

R Markdown output format to pass torender()

About Math support

Default behavior is to keep any inline equation using$ and any blockequation using⁠$$⁠ in the resulting markdown as Github will process thoseusing Mathjax.This feature is only available with Pandoc 2.10.1 and above

When using"webtex", PNG images with a white background are used by default sothat it shows correctly on Github on both light and dark theme. You canchoose to only output SVG for better quality by changing the URL used:

output:  github_document:    math_method:      engine: webtex      url: https://latex.codecogs.com/svg.image?

Background or fonts color cannot be changed for now and your equation may not be visible on dark theme.

Using"webtex" will be the default with Pandoc 2.0.4 until Pandoc 2.10. Before 2.0.4, Github document output does not support math.


Provide common HTML dependencies for R Markdown formats

Description

These functions provide common HTML dependencies (e.g. jquery, bootstrap)for re-use by other R Markdown formats.

Usage

html_dependency_jquery()html_dependency_jqueryui()html_dependency_bootstrap(theme)html_dependency_tocify()html_dependency_font_awesome()html_dependency_ionicons()html_dependency_pagedtable()html_dependency_highlightjs(highlight)html_dependency_tabset()html_dependency_codefolding_lua()

Arguments

theme

One of the following:

  • Abslib::bs_theme() object (or a list ofbslib::bs_theme() argument values)

    • Use this option for custom themes using Bootstrap 4 or 3.

    • In this case, any.scss/.sass files provided to thecssparameter may utilize thetheme's underlying Sass utilities(e.g., variables, mixins, etc).

  • NULL for no theme (i.e., nohtml_dependency_bootstrap()).

  • A character string specifying aBootswatch 3theme name (for backwards-compatibility).

highlight

Highlighter to use


Convert to an HTML document

Description

Format for converting from R Markdown to an HTML document.

Usage

html_document(  toc = FALSE,  toc_depth = 3,  toc_float = FALSE,  number_sections = FALSE,  anchor_sections = FALSE,  section_divs = TRUE,  fig_width = 7,  fig_height = 5,  fig_retina = 2,  fig_caption = TRUE,  dev = "png",  df_print = "default",  code_folding = c("none", "show", "hide"),  code_download = FALSE,  self_contained = TRUE,  theme = "default",  highlight = "default",  highlight_downlit = FALSE,  math_method = "default",  mathjax = "default",  template = "default",  extra_dependencies = NULL,  css = NULL,  includes = NULL,  keep_md = FALSE,  lib_dir = NULL,  md_extensions = NULL,  pandoc_args = NULL,  ...)

Arguments

toc

TRUE to include a table of contents in the output

toc_depth

Depth of headers to include in table of contents

toc_float

TRUE to float the table of contents to the left of themain document content. Rather thanTRUE you may also pass a list ofoptions that control the behavior of the floating table of contents. See theFloating Table of Contents section below for details.

number_sections

TRUE to number section headings

anchor_sections

TRUE to show section anchors when mouse hoversfor all headers. A list can also be passed withstyle and/ordepth to customize the behavior. SeeAnchor Sections Customization section.

section_divs

Wrap sections in⁠<div>⁠ tags, and attach identifiers to theenclosing⁠<div>⁠ rather than the header itself.

fig_width

Default width (in inches) for figures

fig_height

Default height (in inches) for figures

fig_retina

Scaling to perform for retina displays (defaults to 2, whichcurrently works for all widely used retina displays). Set toNULL toprevent retina scaling. Note that this will always beNULL whenkeep_md is specified (this is becausefig_retina relies onoutputting HTML directly into the markdown document).

fig_caption

TRUE to render figures with captions

dev

Graphics device to use for figure output (defaults to png)

df_print

Method to be used for printing data frames. Valid valuesinclude "default", "kable", "tibble", and "paged". The "default" methoduses a corresponding S3 method ofprint, typicallyprint.data.frame. The "kable" method uses theknitr::kable function. The "tibble" method usesthetibble package to print a summary of the data frame. The "paged"method creates a paginated HTML table (note that this method is only validfor formats that produce HTML). In addition to the named methods you canalso pass an arbitrary function to be used for printing data frames. Youcan disable thedf_print behavior entirely by setting the optionrmarkdown.df_print toFALSE. SeeDataframe printing section in bookdown book for examples.

code_folding

Enable document readers to toggle the display of R codechunks. Specify"none" to display all code chunks. Specify"hide" or"show" to hide or show all R code chunks bydefault, and let readers toggle the states on browsers. See theCode folding

code_download

Embed the Rmd source code within the document and providea link that can be used by readers to download the code.

self_contained

Produce a standalone HTML file with no externaldependencies, using data: URIs to incorporate the contents of linkedscripts, stylesheets, images, and videos. Note that even for self containeddocuments MathJax is still loaded externally (this is necessary because ofits size).

theme

One of the following:

  • Abslib::bs_theme() object (or a list ofbslib::bs_theme() argument values)

    • Use this option for custom themes using Bootstrap 4 or 3.

    • In this case, any.scss/.sass files provided to thecssparameter may utilize thetheme's underlying Sass utilities(e.g., variables, mixins, etc).

  • NULL for no theme (i.e., nohtml_dependency_bootstrap()).

  • A character string specifying aBootswatch 3theme name (for backwards-compatibility).

highlight

Syntax highlight engine and style. See theHighlighting section below for details.

"default" (and "textmate") will use highlightjs as syntax highlightingengine instead of Pandoc.

Any other value will be passed as Pandoc's highlighting style. Pandoc'sbuilt-in styles include "tango", "pygments", "kate", "monochrome","espresso", "zenburn", "haddock" and "breezedark".

Two custom styles are also included, "arrow", an accessible color scheme,and "rstudio", which mimics the default IDE theme. Alternatively, supply apath to a ‘⁠.theme⁠’ to usea custom Pandoc style. Note that custom theme requires Pandoc 2.0+.

PassNULL to prevent syntax highlighting.

highlight_downlit

TRUE to use thedownlit package assyntax highlight engine to highlight inline code and R code chunks(including providing hyperlinks to function documentation). The packageneeds to be installed to use this feature.

Only Pandoc color schemes are supported with this engine. Withhighlight = "default", it will use the accessible theme called"arrow". To learn more aboutdownlit highlighting engine, seehttps://downlit.r-lib.org/.

math_method

Math rendering engine to use. This will define the math method to use with Pandoc.

  • It can be a string for the engine, one of "mathjax", "mathml", "webtex", "katex", "gladtex", or "r-katex"or "default" formathjax.

  • It can be a list of

    • engine: one of"mathjax", "mathml", "webtex", "katex", or "gladtex".

    • url: A specific url to use withmathjax,katex orwebtex.Note that forengine = "mathjax",url = "local" will use a local version of MathJax (which iscopied into the output directory).

For example,

output:  html_document:    math_method:      engine: katex      url: https://cdn.jsdelivr.net/npm/katex@0.11.1/dist

SeePandoc's Manual about Math in HTML for the detailsabout Pandoc supported methods.

Usingmath_method = "r-katex" will opt-in server side rendering usingKaTeX thanks tokatex R package. This isuseful compared tomath_method = "katex" to have no JS dependency, only aCSS dependency for styling equation.

mathjax

Include mathjax. The "default" option uses an https URL from aMathJax CDN. The "local" option uses a local version of MathJax (which iscopied into the output directory). You can pass an alternate URL or passNULL to exclude MathJax entirely.

template

Pandoc template to use for rendering. Pass "default" to usethe rmarkdown package default template; passNULL to use pandoc'sbuilt-in template; pass a path to use a custom template that you've created.Note that if you don't use the "default" template then some features ofhtml_document won't be available (see the Templates section below formore details).

extra_dependencies

Extra dependencies as a list of thehtml_dependency class objects typically generated byhtmltools::htmlDependency().

css

CSS and/or Sass files to include. Files with an extension of .sassor .scss are compiled to CSS viasass::sass(). Also, iftheme is abslib::bs_theme() object, Sass code may reference the relevant BootstrapSass variables, functions, mixins, etc.

includes

Named list of additional content to include within thedocument (typically created using theincludes function).

keep_md

Keep the markdown file generated by knitting.

lib_dir

Directory to copy dependent HTML libraries (e.g. jquery,bootstrap, etc.) into. By default this will be the name of the document with⁠_files⁠ appended to it.

md_extensions

Markdown extensions to be added or removed from thedefault definition of R Markdown. See thermarkdown_format foradditional details.

pandoc_args

Additional command line options to pass to pandoc

...

Additional function arguments to pass to the base R Markdown HTMLoutput formatterhtml_document_base

Details

See theonline documentation for additional details on using thehtml_documentformat.

R Markdown documents can have optional metadata that is used to generate adocument header that includes the title, author, and date. For more detailssee the documentation on R Markdownmetadata.

R Markdown documents also support citations. You can find more information onthe markdown syntax for citations in theBibliographies and Citations article in the online documentation.

Value

R Markdown output format to pass torender

Highlighting

There are three highlighting engines available to HTML documents:

highlightjs

It does highlighting in the browser, using javascript Itcan only be used with the default template (i.etemplate = "default")and it has two styles ("default" and "textmate"). When activated, it addstwo additional dependencies to the output file: a JS script and a CSS file.For now, this is the default engine for the default template - this couldchange in the future.

Pandoc

Pandoc's built-in highlighting.engine works with any template,default or custom, and style can be chosen among the built-in ones ("tango","pygments", "kate", "monochrome", "espresso", "zenburn", "haddock" and"breezedark") or a path to a custom theme ".theme" file (see Details in thePandoc Manual).rmarkdown includes two custom themes to select withhighlightparameter:

Custom themes are only available for Pandoc 2.0 and above.

downlit

downlit is an R package thatprovides a syntax highlighting engine in R. It will also do automaticlinking of R code (requires internet connectivity). It is activated only ifhighlight_downlit = TRUE and only affects R code, leavinghighlighting for other languages unchanged. The default color scheme isthe accessible theme "arrow".

It requires some CSS in the template to correctly style links. This is includedin the default template, but if you want to use with a custom template, you willneed to add this to your template:

$if(highlight-downlit)$<style type="text/css">  code a:any-link {   color: inherit; /* use colour from syntax highlighting */   text-decoration: underline;   text-decoration-color: #ccc;  }</style>$endif$

Anchor Sections Customization

This will be the default to activate anchor sections link on header

output:  html_document:    anchor_sections: TRUE

There are currently two options to modify the default behavior

style

Select a predefined visual style:

  • style = "dash", the default, uses ‘⁠#⁠’, a minimalist choice that evokes the id selector from HTML and CSS.

  • style = "symbol" will use alink symbol (🔗︎)

  • style = "icon" will use an svg icon. (icon link)

You can also customize using a css rule in yourdocument. For example, to get a pictogram (🔗):

a.anchor-section::before {  content: '\\01F517';}

About how to apply custom CSS in R Markdown document, seehttps://bookdown.org/yihui/rmarkdown-cookbook/html-css.html

depth

Select the maximum header level to add theanchor link to. For example, this yaml will use the symbol style andonly with level 1 and 2 headings:

output:  html_document:    anchor_sections:      style: icon      depth: 2

If omitted, anchor will be added to all headers (equivalent ofdepth=6). You can also set anchors manually withdepth = 0 using this syntax

# my header {.hasAnchor}

Using anchor sections will add some CSS to your document output for thestyling, and a JS script ifsection_divs = TRUE. The anchor link itselfis added using a Lua filter, and hence requires Pandoc 2.0+

Navigation Bars

If you have a set of html documents which you'd like to provide a commonglobal navigation bar for, you can include a "_navbar.yml" or "_navbar.html"file within the same directory as your html document and it will automaticallybe included at the top of the document.

The "_navbar.yml" file includestitle,type,left, andright fields (to define menu items for the left and right of the navbarrespectively). Menu items includetext andhref fields. For example:

title: "My Website"type: defaultleft:  - text: "Home"    href: index.html  - text: "Other"    href: other.htmlright:  - text: GitHub    href: https://github.com

Thetype field is optional and can take the value "default" or "inverse" (whichprovides a different color scheme for the navigation bar).

Alternatively, you can include a "_navbar.html" file which is a full HTML definitionof a bootstrap navigation bar. For a simple example of including a navigation bar seehttps://github.com/rstudio/rmarkdown-website/blob/master/_navbar.html.For additional documentation on creating Bootstrap navigation bars seehttps://getbootstrap.com/docs/4.5/components/navbar/.

Floating Table of Contents

You may specify a list of options for thetoc_float parameter whichcontrol the behavior of the floating table of contents. Options include:

Code folding

Code blocks become foldable by specifying "show" or "hide" to thecode_folding parameter. The state can be toggled individually onbrowsers. The document-wide toggle button is also provided forhtml_document and some of its extensions such ashtml_notebook. Note that this feature applies not only to sourcecodes of chunks, but also markdown code blocks.

Supported languages are R, Python, Bash, SQL, C++, Stan, and Julia. Tosupport code blocks with other languages, addfoldable class to them(i.e.,class.source = "foldable" as a chunk option).

The default initial state of code folding respects the value given to thecode_folding parameter. To override the behavior individually, addfold-none to disable,fold-hide to initially hide,fold-show to initially show.

Tabbed Sections

You can organize content using tabs by applying the.tabset classattribute to headers within a document. This will cause all sub-headers ofthe header with the.tabset attribute to appear within tabs ratherthan as standalone sections. For example:

## Quarterly Results {.tabset}### By Product### By Region

Withhtml_document(), you can also specify two additional attributes tocontrol the appearance and behavior of the tabs. The.tabset-fadeattributes causes the tabs to fade in and out when switching. The.tabset-pills attribute causes the visual appearance of the tabs tobe "pill" rather than traditional tabs. For example:

## Quarterly Results {.tabset .tabset-fade .tabset-pills}

If tabbed sections relies onhtml_dependency_tabset(), for example byhtml_vignette(), these two attributes are not supported.

Templates

You can provide a custom HTML template to be used for rendering. The syntaxfor templates is described in thepandoc documentation. You can also usethe basic pandoc template by passingtemplate = NULL.

Note however that if you choose not to use the "default" HTML template thenseveral aspects of HTML document rendering will behave differently:

Due to the above restrictions, you might consider using theincludesparameter as an alternative to providing a fully custom template.

Examples

## Not run: library(rmarkdown)render("input.Rmd", html_document())render("input.Rmd", html_document(toc = TRUE))## End(Not run)

Base output format for HTML-based output formats

Description

Creates an HTML base output format suitable for passing as thebase_format argument of theoutput_format function.

Usage

html_document_base(  theme = NULL,  self_contained = TRUE,  lib_dir = NULL,  math_method = "default",  mathjax = "default",  pandoc_args = NULL,  template = "default",  dependency_resolver = NULL,  copy_resources = FALSE,  extra_dependencies = NULL,  css = NULL,  bootstrap_compatible = FALSE,  ...)

Arguments

theme

One of the following:

  • Abslib::bs_theme() object (or a list ofbslib::bs_theme() argument values)

    • Use this option for custom themes using Bootstrap 4 or 3.

    • In this case, any.scss/.sass files provided to thecssparameter may utilize thetheme's underlying Sass utilities(e.g., variables, mixins, etc).

  • NULL for no theme (i.e., nohtml_dependency_bootstrap()).

  • A character string specifying aBootswatch 3theme name (for backwards-compatibility).

self_contained

Produce a standalone HTML file with no externaldependencies, using data: URIs to incorporate the contents of linkedscripts, stylesheets, images, and videos. Note that even for self containeddocuments MathJax is still loaded externally (this is necessary because ofits size).

lib_dir

Directory to copy dependent HTML libraries (e.g. jquery,bootstrap, etc.) into. By default this will be the name of the document with⁠_files⁠ appended to it.

math_method

Math rendering engine to use. This will define the math method to use with Pandoc.

  • It can be a string for the engine, one of "mathjax", "mathml", "webtex", "katex", "gladtex", or "r-katex"or "default" formathjax.

  • It can be a list of

    • engine: one of"mathjax", "mathml", "webtex", "katex", or "gladtex".

    • url: A specific url to use withmathjax,katex orwebtex.Note that forengine = "mathjax",url = "local" will use a local version of MathJax (which iscopied into the output directory).

For example,

output:  html_document:    math_method:      engine: katex      url: https://cdn.jsdelivr.net/npm/katex@0.11.1/dist

SeePandoc's Manual about Math in HTML for the detailsabout Pandoc supported methods.

Usingmath_method = "r-katex" will opt-in server side rendering usingKaTeX thanks tokatex R package. This isuseful compared tomath_method = "katex" to have no JS dependency, only aCSS dependency for styling equation.

mathjax

Include mathjax. The "default" option uses an https URL from aMathJax CDN. The "local" option uses a local version of MathJax (which iscopied into the output directory). You can pass an alternate URL or passNULL to exclude MathJax entirely.

pandoc_args

Additional command line options to pass to pandoc

template

Pandoc template to use for rendering. Pass "default" to usethe rmarkdown package default template; passNULL to use pandoc'sbuilt-in template; pass a path to use a custom template that you've created.Note that if you don't use the "default" template then some features ofhtml_document won't be available (see the Templates section below formore details).

dependency_resolver

A dependency resolver

copy_resources

Copy resources

extra_dependencies

Extra dependencies as a list of thehtml_dependency class objects typically generated byhtmltools::htmlDependency().

css

CSS and/or Sass files to include. Files with an extension of .sassor .scss are compiled to CSS viasass::sass(). Also, iftheme is abslib::bs_theme() object, Sass code may reference the relevant BootstrapSass variables, functions, mixins, etc.

bootstrap_compatible

Bootstrap compatible

...

Ignored

Value

HTML base output format.


Convert to an HTML fragment.

Description

An html fragment is suitable for inclusion into an external html page. Seehtml_document for full details - this is a minor variation thatassumes you will include the output into an existing document (e.g. a blogpost).

Usage

html_fragment(  number_sections = FALSE,  section_divs = TRUE,  fig_width = 7,  fig_height = 5,  fig_retina = 2,  fig_caption = TRUE,  dev = "png",  df_print = "default",  mathjax = TRUE,  includes = NULL,  keep_md = FALSE,  md_extensions = NULL,  pandoc_args = NULL,  ...)

Arguments

number_sections

TRUE to number section headings

section_divs

Wrap sections in⁠<div>⁠ tags, and attach identifiers to theenclosing⁠<div>⁠ rather than the header itself.

fig_width

Default width (in inches) for figures

fig_height

Default height (in inches) for figures

fig_retina

Scaling to perform for retina displays (defaults to 2, whichcurrently works for all widely used retina displays). Set toNULL toprevent retina scaling. Note that this will always beNULL whenkeep_md is specified (this is becausefig_retina relies onoutputting HTML directly into the markdown document).

fig_caption

TRUE to render figures with captions

dev

Graphics device to use for figure output (defaults to png)

df_print

Method to be used for printing data frames. Valid valuesinclude "default", "kable", "tibble", and "paged". The "default" methoduses a corresponding S3 method ofprint, typicallyprint.data.frame. The "kable" method uses theknitr::kable function. The "tibble" method usesthetibble package to print a summary of the data frame. The "paged"method creates a paginated HTML table (note that this method is only validfor formats that produce HTML). In addition to the named methods you canalso pass an arbitrary function to be used for printing data frames. Youcan disable thedf_print behavior entirely by setting the optionrmarkdown.df_print toFALSE. SeeDataframe printing section in bookdown book for examples.

mathjax

TRUE to convert $ and $$ math blocks into MathJaxcompatible output. Note that you'll still need to ensure that the pagewhere the fragment is included loads the required MathJax scripts.

includes

Named list of additional content to include within thedocument (typically created using theincludes function).

keep_md

Keep the markdown file generated by knitting.

md_extensions

Markdown extensions to be added or removed from thedefault definition of R Markdown. See thermarkdown_format foradditional details.

pandoc_args

Additional command line options to pass to pandoc

...

Additional arguments passed tohtml_document

Details

See theonlinedocumentation for additional details on using thehtml_fragmentformat.

Value

R Markdown output format to pass torender


Convert to an HTML notebook

Description

Format for converting from R Markdown to an HTML notebook.

Usage

html_notebook(  toc = FALSE,  toc_depth = 3,  toc_float = FALSE,  number_sections = FALSE,  fig_width = 7,  fig_height = 5,  fig_retina = 2,  fig_caption = TRUE,  code_folding = "show",  theme = "default",  highlight = "textmate",  highlight_downlit = FALSE,  math_method = "default",  mathjax = "default",  extra_dependencies = NULL,  css = NULL,  includes = NULL,  md_extensions = NULL,  pandoc_args = NULL,  output_source = NULL,  self_contained = TRUE,  ...)

Arguments

toc

TRUE to include a table of contents in the output

toc_depth

Depth of headers to include in table of contents

toc_float

TRUE to float the table of contents to the left of themain document content. Rather thanTRUE you may also pass a list ofoptions that control the behavior of the floating table of contents. See theFloating Table of Contents section below for details.

number_sections

TRUE to number section headings

fig_width

Default width (in inches) for figures

fig_height

Default height (in inches) for figures

fig_retina

Scaling to perform for retina displays (defaults to 2, whichcurrently works for all widely used retina displays). Set toNULL toprevent retina scaling. Note that this will always beNULL whenkeep_md is specified (this is becausefig_retina relies onoutputting HTML directly into the markdown document).

fig_caption

TRUE to render figures with captions

code_folding

Enable document readers to toggle the display of R codechunks. Specify"none" to display all code chunks. Specify"hide" or"show" to hide or show all R code chunks bydefault, and let readers toggle the states on browsers. See theCode folding

theme

One of the following:

  • Abslib::bs_theme() object (or a list ofbslib::bs_theme() argument values)

    • Use this option for custom themes using Bootstrap 4 or 3.

    • In this case, any.scss/.sass files provided to thecssparameter may utilize thetheme's underlying Sass utilities(e.g., variables, mixins, etc).

  • NULL for no theme (i.e., nohtml_dependency_bootstrap()).

  • A character string specifying aBootswatch 3theme name (for backwards-compatibility).

highlight

Syntax highlight engine and style. See theHighlighting section below for details.

"default" (and "textmate") will use highlightjs as syntax highlightingengine instead of Pandoc.

Any other value will be passed as Pandoc's highlighting style. Pandoc'sbuilt-in styles include "tango", "pygments", "kate", "monochrome","espresso", "zenburn", "haddock" and "breezedark".

Two custom styles are also included, "arrow", an accessible color scheme,and "rstudio", which mimics the default IDE theme. Alternatively, supply apath to a ‘⁠.theme⁠’ to usea custom Pandoc style. Note that custom theme requires Pandoc 2.0+.

PassNULL to prevent syntax highlighting.

highlight_downlit

TRUE to use thedownlit package assyntax highlight engine to highlight inline code and R code chunks(including providing hyperlinks to function documentation). The packageneeds to be installed to use this feature.

Only Pandoc color schemes are supported with this engine. Withhighlight = "default", it will use the accessible theme called"arrow". To learn more aboutdownlit highlighting engine, seehttps://downlit.r-lib.org/.

math_method

Math rendering engine to use. This will define the math method to use with Pandoc.

  • It can be a string for the engine, one of "mathjax", "mathml", "webtex", "katex", "gladtex", or "r-katex"or "default" formathjax.

  • It can be a list of

    • engine: one of"mathjax", "mathml", "webtex", "katex", or "gladtex".

    • url: A specific url to use withmathjax,katex orwebtex.Note that forengine = "mathjax",url = "local" will use a local version of MathJax (which iscopied into the output directory).

For example,

output:  html_document:    math_method:      engine: katex      url: https://cdn.jsdelivr.net/npm/katex@0.11.1/dist

SeePandoc's Manual about Math in HTML for the detailsabout Pandoc supported methods.

Usingmath_method = "r-katex" will opt-in server side rendering usingKaTeX thanks tokatex R package. This isuseful compared tomath_method = "katex" to have no JS dependency, only aCSS dependency for styling equation.

mathjax

Include mathjax. The "default" option uses an https URL from aMathJax CDN. The "local" option uses a local version of MathJax (which iscopied into the output directory). You can pass an alternate URL or passNULL to exclude MathJax entirely.

extra_dependencies

Extra dependencies as a list of thehtml_dependency class objects typically generated byhtmltools::htmlDependency().

css

CSS and/or Sass files to include. Files with an extension of .sassor .scss are compiled to CSS viasass::sass(). Also, iftheme is abslib::bs_theme() object, Sass code may reference the relevant BootstrapSass variables, functions, mixins, etc.

includes

Named list of additional content to include within thedocument (typically created using theincludes function).

md_extensions

Markdown extensions to be added or removed from thedefault definition of R Markdown. See thermarkdown_format foradditional details.

pandoc_args

Additional command line options to pass to pandoc

output_source

Define an output source forR chunks (ie,outputs to use instead of those produced by evaluating theunderlyingR code). Seehtml_notebook_output formore details.

self_contained

Produce a standalone HTML file with no externaldependencies. Defaults toTRUE. In notebooks, setting this toFALSE is not recommended, since the setting does not apply toembedded notebook output such as plots and HTML widgets.

...

Additional function arguments to pass to the base R Markdown HTMLoutput formatterhtml_document_base

Details

See theonlinedocumentation for additional details on using thehtml_notebookformat.


Generate R Notebook Metadata

Description

A structured helper for the construction of metadata used by theR Notebook output functions. Seehtml_notebook_output formore details.

Usage

html_notebook_metadata(iframe = TRUE)

Arguments

iframe

Boolean; should output be shown in an<iframe>?


Generate R Notebook Output

Description

Utilities for generating output for thehtml_notebook format,through theoutput_source function attached to aoutput_format.

Usage

html_notebook_output_html(html, meta = NULL)html_notebook_output_img(  path = NULL,  bytes = NULL,  attributes = NULL,  meta = NULL,  format = c("png", "jpeg"))html_notebook_output_png(  path = NULL,  bytes = NULL,  attributes = NULL,  meta = NULL,  format = c("png", "jpeg"))html_notebook_output_code(code, attributes = list(class = "r"), meta = NULL)

Arguments

html

Arbitrary HTML content to insert.

meta

AnR list of arbitrary meta-data. The data willbe converted to JSON, base64-encoded, and injected into the header comment.

path

A path to a file. For functions accepting bothpathandbytes, ifbytes isNULL, the bytewise contentswill be obtained by reading the file.

bytes

The bytewise representation of content.

attributes

A namedR list of HTML attributes. These will beescaped and inserted into the generated HTML as appropriate.

format

The image format; one of"png" or"jpeg".

code

Source code.

Details

See theonlinedocumentation for additional details on using thehtml_notebookformat.


Convert to an HTML vignette

Description

A HTML vignette is a lightweight alternative tohtml_document()suitable for inclusion in packages to be released to CRAN. It reduces thesize of a basic vignette from 100k to around 10k.

Usage

html_vignette(  fig_width = 3,  fig_height = 3,  dev = "png",  df_print = "default",  css = NULL,  highlight = "pygments",  keep_md = FALSE,  readme = FALSE,  self_contained = TRUE,  tabset = FALSE,  code_folding = c("none", "show", "hide"),  extra_dependencies = NULL,  pandoc_args = NULL,  ...)

Arguments

fig_width

Default width (in inches) for figures

fig_height

Default height (in inches) for figures

dev

Graphics device to use for figure output (defaults to png)

df_print

Method to be used for printing data frames. Valid valuesinclude "default", "kable", "tibble", and "paged". The "default" methoduses a corresponding S3 method ofprint, typicallyprint.data.frame. The "kable" method uses theknitr::kable function. The "tibble" method usesthetibble package to print a summary of the data frame. The "paged"method creates a paginated HTML table (note that this method is only validfor formats that produce HTML). In addition to the named methods you canalso pass an arbitrary function to be used for printing data frames. Youcan disable thedf_print behavior entirely by setting the optionrmarkdown.df_print toFALSE. SeeDataframe printing section in bookdown book for examples.

css

One or more css files to include.

highlight,...

Additional arguments passed tohtml_document(). Please note thattheme andfig_retina are hard-coded. Setting any of those will yield an error.

keep_md

Keep the markdown file generated by knitting.

readme

Use this vignette as the package README.md file (i.e. renderit as README.md to the package root). Note that if there are image fileswithin your vignette you should be sure to add ‘README_files’ to ‘.Rbuildignore’.

self_contained

Produce a standalone HTML file with no externaldependencies, using data: URIs to incorporate the contents of linkedscripts, stylesheets, images, and videos. Note that even for self containeddocuments MathJax is still loaded externally (this is necessary because ofits size).

tabset

Opt-in tabbed-sections feature inspired byhtml_document().See section "Tabbed Sections" for the detail.This feature also allows navigation to the tab from table of contents and URL.

code_folding

Enable document readers to toggle the display of R codechunks. Specify"none" to display all code chunks. Specify"hide" or"show" to hide or show all R code chunks bydefault, and let readers toggle the states on browsers. See theCode folding

extra_dependencies

Extra dependencies as a list of thehtml_dependency class objects typically generated byhtmltools::htmlDependency().

pandoc_args

Additional command line options to pass to pandoc

Details

Compared tohtml_document(), it:

See theonline documentationfor additional details on using thehtml_vignette() format.

Value

R Markdown output format to pass torender()

Tabbed Sections

You can organize content using tabs by applying the.tabset classattribute to headers within a document. This will cause all sub-headers ofthe header with the.tabset attribute to appear within tabs ratherthan as standalone sections. For example:

## Quarterly Results {.tabset}### By Product### By Region

Withhtml_document(), you can also specify two additional attributes tocontrol the appearance and behavior of the tabs. The.tabset-fadeattributes causes the tabs to fade in and out when switching. The.tabset-pills attribute causes the visual appearance of the tabs tobe "pill" rather than traditional tabs. For example:

## Quarterly Results {.tabset .tabset-fade .tabset-pills}

If tabbed sections relies onhtml_dependency_tabset(), for example byhtml_vignette(), these two attributes are not supported.

Code folding

Code blocks become foldable by specifying "show" or "hide" to thecode_folding parameter. The state can be toggled individually onbrowsers. The document-wide toggle button is also provided forhtml_document and some of its extensions such ashtml_notebook. Note that this feature applies not only to sourcecodes of chunks, but also markdown code blocks.

Supported languages are R, Python, Bash, SQL, C++, Stan, and Julia. Tosupport code blocks with other languages, addfoldable class to them(i.e.,class.source = "foldable" as a chunk option).

The default initial state of code folding respects the value given to thecode_folding parameter. To override the behavior individually, addfold-none to disable,fold-hide to initially hide,fold-show to initially show.


Include content within output

Description

Specify additional content to be included within an output document.

Usage

includes(in_header = NULL, before_body = NULL, after_body = NULL)includes_to_pandoc_args(includes, filter = identity)

Arguments

in_header

One or more files with content to be included in theheader of the document.

before_body

One or more files with content to be included beforethe document body.

after_body

One or more files with content to be included after thedocument body.

includes

Includes to convert to pandoc args.

filter

Filter to pre-process includes with.

Details

Non-absolute paths for resources referenced from thein_header,before_body, andafter_bodyparameters are resolved relative to the directory of the input document.

Value

Includes list or pandoc args

Examples

## Not run: library(rmarkdown)html_document(includes = includes(before_body = "header.htm"))pdf_document(includes = includes(after_body = "footer.tex"))## End(Not run)

Convert to an ioslides Presentation

Description

Format for converting from R Markdown to anioslides presentation.

Usage

ioslides_presentation(  number_sections = FALSE,  logo = NULL,  slide_level = 2,  incremental = FALSE,  fig_width = 7.5,  fig_height = 4.5,  fig_retina = 2,  fig_caption = TRUE,  dev = "png",  df_print = "default",  smart = TRUE,  self_contained = TRUE,  widescreen = FALSE,  smaller = FALSE,  transition = "default",  math_method = "mathjax",  mathjax = "default",  analytics = NULL,  template = NULL,  css = NULL,  includes = NULL,  keep_md = FALSE,  lib_dir = NULL,  md_extensions = NULL,  pandoc_args = NULL,  extra_dependencies = NULL,  ...)

Arguments

number_sections

TRUE to number section headings

logo

Path to file that includes a logo for use in the presentation(should be square and at least 128x128).

slide_level

Header level to consider as slide separator (Defaults toheader 2).

incremental

TRUE to render slide bullets incrementally.Note that if you want to reverse the default incremental behavior for anindividual bullet you can preceded it with>.For example:⁠> - Bullet Text⁠.

fig_width

Default width (in inches) for figures

fig_height

Default height (in inches) for figures

fig_retina

Scaling to perform for retina displays (defaults to 2, whichcurrently works for all widely used retina displays). Set toNULL toprevent retina scaling. Note that this will always beNULL whenkeep_md is specified (this is becausefig_retina relies onoutputting HTML directly into the markdown document).

fig_caption

TRUE to render figures with captions

dev

Graphics device to use for figure output (defaults to png)

df_print

Method to be used for printing data frames. Valid valuesinclude "default", "kable", "tibble", and "paged". The "default" methoduses a corresponding S3 method ofprint, typicallyprint.data.frame. The "kable" method uses theknitr::kable function. The "tibble" method usesthetibble package to print a summary of the data frame. The "paged"method creates a paginated HTML table (note that this method is only validfor formats that produce HTML). In addition to the named methods you canalso pass an arbitrary function to be used for printing data frames. Youcan disable thedf_print behavior entirely by setting the optionrmarkdown.df_print toFALSE. SeeDataframe printing section in bookdown book for examples.

smart

Produce typographically correct output, converting straightquotes to curly quotes,⁠---⁠ to em-dashes,⁠--⁠ to en-dashes, and... to ellipses.

self_contained

Produce a standalone HTML file with no externaldependencies, using data: URIs to incorporate the contents of linkedscripts, stylesheets, images, and videos. Note that even for self containeddocuments MathJax is still loaded externally (this is necessary because ofits size).

widescreen

Display presentation with wider dimensions.

smaller

Use smaller text on all slides. You can also enable this forindividual slides by adding the.smaller attribute to the slideheader (seePresentation Size below for details).

transition

Speed of slide transitions. This can be "default","slower", "faster", or a numeric value with a number of seconds (e.g. 0.5).

math_method

Math rendering engine to use. This will define the math method to use with Pandoc.

  • It can be a string for the engine, one of "mathjax", "mathml", "webtex", "katex", "gladtex", or "r-katex"or "default" formathjax.

  • It can be a list of

    • engine: one of"mathjax", "mathml", "webtex", "katex", or "gladtex".

    • url: A specific url to use withmathjax,katex orwebtex.Note that forengine = "mathjax",url = "local" will use a local version of MathJax (which iscopied into the output directory).

For example,

output:  html_document:    math_method:      engine: katex      url: https://cdn.jsdelivr.net/npm/katex@0.11.1/dist

SeePandoc's Manual about Math in HTML for the detailsabout Pandoc supported methods.

Usingmath_method = "r-katex" will opt-in server side rendering usingKaTeX thanks tokatex R package. This isuseful compared tomath_method = "katex" to have no JS dependency, only aCSS dependency for styling equation.

mathjax

Include mathjax. The "default" option uses an https URL from aMathJax CDN. The "local" option uses a local version of MathJax (which iscopied into the output directory). You can pass an alternate URL or passNULL to exclude MathJax entirely.

analytics

A Google analytics property ID.

template

Pandoc template to use for rendering. Pass "default" to usethe rmarkdown package default template; passNULL to use pandoc'sbuilt-in template; pass a path to use a custom template that you've created.Note that if you don't use the "default" template then some features ofhtml_document won't be available (see the Templates section below formore details).

css

One or more css files to include.

includes

Named list of additional content to include within thedocument (typically created using theincludes function).

keep_md

Keep the markdown file generated by knitting.

lib_dir

Directory to copy dependent HTML libraries (e.g. jquery,bootstrap, etc.) into. By default this will be the name of the document with⁠_files⁠ appended to it.

md_extensions

Markdown extensions to be added or removed from thedefault definition of R Markdown. See thermarkdown_format foradditional details.

pandoc_args

Additional command line options to pass to pandoc

extra_dependencies

Extra dependencies as a list of thehtml_dependency class objects typically generated byhtmltools::htmlDependency().

...

Additional function arguments to pass to the base R Markdown HTMLoutput formatterhtml_document_base

Details

See the online documentation for additional details on using theioslides_presentation format.

Note that, if abefore_body include is specified inincludes,then it will replace the standard title slide entirely.

Regarding previewing slide in RStudio IDE,ioslides_presentation() willalways open preview in a new Window and the RStudio IDE configuration "Open in ViewerPane" will have no effect for this format.

Value

R Markdown output format to pass torender().

Slide Basics

You can create a slide show broken up into sections by using the # and ##heading tags (you can also create a new slide without a header using ahorizontal rule (⁠----------⁠). For example here's a simple slide show:

---title: "Habits"author: John Doedate: March 22, 2005output: ioslides_presentation---# In the morning## Getting up- Turn off alarm- Get out of bed## Breakfast- Eat eggs- Drink coffee# In the evening## Dinner- Eat spaghetti- Drink wine----------![picture of spaghetti](images/spaghetti.jpg)## Going to sleep- Get in bed- Count sheep

You can add a subtitle to a slide or section by including text after thepipe (|) character. For example:

## Getting up | What I like to do first thing

Display Modes

The following single character keyboard shortcuts enable alternate displaymodes:

'f'

enable fullscreen mode

'w'

toggle widescreen mode

'o'

enable overview mode

'h'

enable code highlight mode

'p'

show presenter notes

PressingEsc exits all of these modes. See the sections below onCode Highlighting andPresenter Mode for additionaldetail on those modes.

Incremental Bullets

You can render bullets incrementally by adding theincrementaloption:

---output:  ioslides_presentation:    incremental: true---

If you want to render bullets incrementally for some slides but notothers you can use this syntax:

> - Eat eggs> - Drink coffee

Presentation Size

You can display the presentation using a wider form factor using thewidescreen option. You can specify that smaller text be used withthesmaller option. For example:

---output:  ioslides_presentation:    widescreen: true    smaller: true---

You can also enable thesmaller option on a slide-by-slide basisby adding the.smaller attribute to the slide header:

## Getting up {.smaller}

Adding a Logo

You can add a logo to the presentation using thelogo option (thelogo should be square and at least 128x128). For example:

---output:  ioslides_presentation:    logo: logo.png---

A 128x128 version of the logo graphic will be added to the title slide andan icon version of the logo will be included in the bottom-left footer ofeach slide.

Build Slides

Slides can also have a.build attribute that indicate that theircontent should be displayed incrementally. For example:

## Getting up {.build}

Slide attributes can be combined if you need to specify more than one,for example:

## Getting up {.smaller .build}

Code Highlighting

It's possible to select subsets of code for additional emphasis by adding aspecial "highlight" comment around the code. For example:

### <b>x <- 10y <- x * 2### </b>

The highlighted region will be displayed with a bold font. When you want tohelp the audience focus exclusively on the highlighted region press the'h' key and the rest of the code will fade away.

Tables

The ioslides template has an attractive default style for tables so youshouldn't hesitate to add tables for presenting more complex sets ofinformation. Pandoc markdown supports several syntaxes for definingtables which are described in thepandoc online documentation.

Advanced Layout

You can center content on a slide by adding the.flexboxand.vcenter attributes to the slide title. For example:

## Dinner {.flexbox .vcenter}

You can horizontally center content by enclosing it in adiv tagwith classcentered. For example:

<div>This text is centered.</div>

You can do a two-column layout using thecolumns-2 class.For example:

<div>  ![Image](image.png)  - Bullet 1  - Bullet 2  - Bullet 3</div>

Note that content will flow across the columns so if you want tohave an image on one side and text on the other you should makesure that the image has sufficient height to force the text tothe other side of the slide.

Text Color

You can color content using base color classes red, blue, green, yellow,and gray (or variations of them e.g. red2, red3, blue2, blue3, etc.).For example:

<div>This text is red</div>

Presenter Mode

A separate presenter window can also be opened (ideal for when you arepresenting on one screen but have another screen that's private to you).The window stays in sync with the main presentation window and alsoshows presenter notes and a thumbnail of the next slide. To enablepresenter mode add?presentme=true to the URL of the presentation,for example:

mypresentation.html?presentme=true

The presenter mode window will open and will always re-open with thepresentation until it's disabled with:

mypresentation.html?presentme=false

To add presenter notes to a slide you include it within a "notes"div. For example:

<div>This is my *note*.- It can contain markdown- like this list</div>

Printing and PDF Output

You can print an ioslides presentation from within browsers that havegood support for print CSS (i.e. as of this writing Google Chromehas the best support). Printing maintains most of the visual stylesof the HTML version of the presentation.

To create a PDF version of a presentation you can use Print to PDFfrom Google Chrome.


Run a shiny application asking for parameter configuration for the given document.

Description

Run a shiny application asking for parameter configuration for the given document.

Usage

knit_params_ask(  file = NULL,  input_lines = NULL,  params = NULL,  shiny_args = NULL,  save_caption = "Save",  encoding = "UTF-8")

Arguments

file

Path to the R Markdown document with configurable parameters.

input_lines

Content of the R Markdown document. IfNULL, the contents offile will be read.

params

A named list of optional parameter overrides used in place of the document defaults.

shiny_args

Additional arguments torunApp.

save_caption

Caption to use use for button that saves/confirms parameters.

encoding

Ignored. The encoding is always assumed to be UTF-8.

Value

named list with overridden parameter names and value.


Knitr options for an output format

Description

Define the knitr options for an R Markdown output format.

Usage

knitr_options(  opts_knit = NULL,  opts_chunk = NULL,  knit_hooks = NULL,  opts_hooks = NULL,  opts_template = NULL)

Arguments

opts_knit

List of package level knitr options (seeopts_knit)

opts_chunk

List of chunk level knitr options (seeopts_chunk)

knit_hooks

List of hooks for R code chunks, inline R code, and output(seeknit_hooks)

opts_hooks

List of hooks for code chunk options(seeopts_hooks)

opts_template

List of templates for chunk level knitr options (seeopts_template)

Value

An list that can be passed as theknitr argumentof theoutput_format function.

See Also

output_format


Knitr options for an HTML output format

Description

Define knitr options for an R Markdown output format that createsHTML output.

Usage

knitr_options_html(fig_width, fig_height, fig_retina, keep_md, dev = "png")

Arguments

fig_width

Default width (in inches) for figures

fig_height

Default height (in inches) for figures

fig_retina

Scaling to perform for retina displays (defaults to 2, whichcurrently works for all widely used retina displays). Set toNULL toprevent retina scaling. Note that this will always beNULL whenkeep_md is specified (this is becausefig_retina relies onoutputting HTML directly into the markdown document).

keep_md

Keep the markdown file generated by knitting.

dev

Graphics device to use for figure output (defaults to png)

Value

An list that can be passed as theknitr argument of theoutput_format function.

See Also

knitr_options,output_format


Knitr options for a PDF output format

Description

Define knitr options for an R Markdown output formatthat creates PDF output.

Usage

knitr_options_pdf(fig_width, fig_height, fig_crop, dev = "pdf")

Arguments

fig_width

Default width (in inches) for figures

fig_height

Default height (in inches) for figures

fig_crop

Whether to crop PDF figures with the commandpdfcrop. This requires the toolspdfcrop andghostscript to be installed. By default,fig_crop = TRUEif these two tools are available.

dev

Graphics device to use for figure output (defaults to png)

Value

An list that can be passed as theknitr argument of theoutput_format function.

See Also

knitr_options,output_format


Provide common LaTeX dependencies

Description

These functions provide common LaTeX dependencies (e.g. tikz)for R Markdown formats that use LaTeX.

Usage

latex_dependency_tikz(libraries, options = NULL, extra_lines = NULL)

Arguments

libraries

A character vector of tikz libraries to load

options

The LaTeX options for the package

extra_lines

LaTeX code related to the package added to the preamble


Define a LaTeX package dependency

Description

Define a LaTeX package dependency

Usage

latex_dependency(name, options = NULL, extra_lines = NULL)

Arguments

name

The LaTeX package name

options

The LaTeX options for the package

extra_lines

LaTeX code related to the package added to the preamble


Convert to a markdown document

Description

Format for converting from R Markdown to another variant of markdown (e.g.strict markdown or github flavored markdown)

Usage

md_document(  variant = "markdown_strict",  preserve_yaml = FALSE,  toc = FALSE,  toc_depth = 3,  number_sections = FALSE,  standalone = FALSE,  fig_width = 7,  fig_height = 5,  fig_retina = NULL,  dev = "png",  df_print = "default",  includes = NULL,  md_extensions = NULL,  pandoc_args = NULL,  ext = ".md")

Arguments

variant

Markdown variant to produce (defaults to "markdown_strict").Other valid values are "commonmark", "gfm", "commonmark_x", "markdown_mmd",markdown_phpextra", "markdown_github", or even "markdown" (which producespandoc markdown). You can also compose custom markdown variants, see thepandoc online documentation fordetails.

preserve_yaml

Preserve YAML front matter in final document.

toc

TRUE to include a table of contents in the output

toc_depth

Depth of headers to include in table of contents

number_sections

TRUE to number section headings

standalone

Set toTRUE to include title, date and other metadatafield in addition to Rmd content as a body.

fig_width

Default width (in inches) for figures

fig_height

Default height (in inches) for figures

fig_retina

Scaling to perform for retina displays. Defaults toNULL which performs no scaling. A setting of 2 will work for allwidely used retina displays, but will also result in the output of⁠<img>⁠ tags rather than markdown images due to the need to set thewidth of the image explicitly.

dev

Graphics device to use for figure output (defaults to png)

df_print

Method to be used for printing data frames. Valid valuesinclude "default", "kable", "tibble", and "paged". The "default" methoduses a corresponding S3 method ofprint, typicallyprint.data.frame. The "kable" method uses theknitr::kable function. The "tibble" method usesthetibble package to print a summary of the data frame. The "paged"method creates a paginated HTML table (note that this method is only validfor formats that produce HTML). In addition to the named methods you canalso pass an arbitrary function to be used for printing data frames. Youcan disable thedf_print behavior entirely by setting the optionrmarkdown.df_print toFALSE. SeeDataframe printing section in bookdown book for examples.

includes

Named list of additional content to include within thedocument (typically created using theincludes function).

md_extensions

Markdown extensions to be added or removed from thedefault definition of R Markdown. See thermarkdown_format foradditional details.

pandoc_args

Additional command line options to pass to pandoc

ext

Extension of the output file (defaults to ".md").

Details

See theonline documentationfor additional details on using themd_document() format.

R Markdown documents can have optional metadata that is used to generate adocument header that includes the title, author, and date. For more detailssee the documentation on R Markdownmetadata.

Value

R Markdown output format to pass torender()

Examples

## Not run: library(rmarkdown)render("input.Rmd", md_document())render("input.Rmd", md_document(variant = "markdown_github"))## End(Not run)

The YAML metadata of the current R Markdown document

Description

The objectmetadata stores the YAML metadata of the current R Markdowndocument as a list, which you may use in the R code chunks, e.g.rmarkdown::metadata$title (the title of the document),rmarkdown::metadata$author, andrmarkdown::metadata$foo (if youhave a YAML field namedfoo), etc.

Format

An object of classlist of length 0.

Examples

rmarkdown::metadata

Description

Create a navbar HTML file from a navbar definition

Usage

navbar_html(navbar)navbar_links_html(links)

Arguments

navbar

Navbar definition

links

List of navbar links

Value

Path to temporary file with navbar definition


Convert to an OpenDocument Text (ODT) document

Description

Format for converting from R Markdown to an ODT document.

Usage

odt_document(  number_sections = FALSE,  fig_width = 5,  fig_height = 4,  fig_caption = TRUE,  template = "default",  reference_odt = "default",  includes = NULL,  keep_md = FALSE,  md_extensions = NULL,  pandoc_args = NULL)

Arguments

number_sections

TRUE to number section headings

fig_width

Default width (in inches) for figures

fig_height

Default height (in inches) for figures

fig_caption

TRUE to render figures with captions

template

Pandoc template to use for rendering. Pass "default" to usethe rmarkdown package default template; passNULL to use pandoc'sbuilt-in template; pass a path to use a custom template that you'vecreated. See the documentation onpandoc online documentation fordetails on creating custom templates.

reference_odt

Use the specified file as a style reference inproducing an odt file. For best results, the reference odt should be amodified version of an odt file produced using pandoc. Pass "default"to use the rmarkdown default styles.

includes

Named list of additional content to include within thedocument (typically created using theincludes function).

keep_md

Keep the markdown file generated by knitting.

md_extensions

Markdown extensions to be added or removed from thedefault definition of R Markdown. See thermarkdown_format foradditional details.

pandoc_args

Additional command line options to pass to pandoc

Details

See theonlinedocumentation for additional details on using theodt_document format.

R Markdown documents can have optional metadata that is used to generate adocument header that includes the title, author, and date. For more detailssee the documentation on R Markdownmetadata.

R Markdown documents also support citations. You can find more information onthe markdown syntax for citations in theBibliographiesand Citations article in the online documentation.

Value

R Markdown output format to pass torender

Examples

## Not run: library(rmarkdown)# simple invocationrender("input.Rmd", odt_document())# specify an option for syntax highlightingrender("input.Rmd", odt_document(highlight = "zenburn"))## End(Not run)

Define an R Markdown output format

Description

Define an R Markdown output format based on a combination of knitr and pandocoptions.

Usage

output_format(  knitr,  pandoc,  keep_md = FALSE,  clean_supporting = TRUE,  df_print = NULL,  pre_knit = NULL,  post_knit = NULL,  pre_processor = NULL,  intermediates_generator = NULL,  post_processor = NULL,  on_exit = NULL,  file_scope = NULL,  base_format = NULL)

Arguments

knitr

Knitr options for an output format (seeknitr_options)

pandoc

Pandoc options for an output format (seepandoc_options)

keep_md

Keep the markdown file generated by knitting. Note that ifthis isTRUE thenclean_supporting will always beFALSE.

clean_supporting

Cleanup any supporting files after conversion seerender_supporting_files

df_print

Method to be used for printing data frames. Valid valuesinclude "default", "kable", "tibble", and "paged". The "default" methoduses a corresponding S3 method ofprint, typicallyprint.data.frame. The "kable" method uses theknitr::kable function. The "tibble" method usesthetibble package to print a summary of the data frame. The "paged"method creates a paginated HTML table (note that this method is only validfor formats that produce HTML). In addition to the named methods you canalso pass an arbitrary function to be used for printing data frames. Youcan disable thedf_print behavior entirely by setting the optionrmarkdown.df_print toFALSE. SeeDataframe printing section in bookdown book for examples.

pre_knit

An optional function that runs before knitting which receivestheinput (input filename passed torender),metadata(the parsed front matter of the Rmd file) and... (for futureexpansion) arguments. This function can be used to add side effects beforeknitting step.

post_knit

An optional function that runs after knitting which receivesthemetadata,input_file,runtime, and... (forfuture expansion) arguments. This function can return additional argumentsto pass to pandoc and can callknitr::knit_meta_add to addadditional dependencies based on the contents of the input_file or on otherassets side by side with it that may be used to produce html withdependencies during subsequent processing.

pre_processor

An optional pre-processor function that receives themetadata,input_file,runtime,knit_meta,files_dir, andoutput_dir and can return additional argumentsto pass to pandoc.

intermediates_generator

An optional function that receives theoriginalinput_file, and the intermediates directory (i.e. theintermediates_dir argument torender). The functionshould generate and return the names of any intermediate files required torender theinput_file.

post_processor

An optional post-processor function that receives themetadata,input_file,output_file,clean, andverbose parameters, and can return an alternativeoutput_file.

on_exit

A function to call whenrmarkdown::render() finishesexecution (as registered with aon.exit handler).

file_scope

A function that will split markdown input to pandoc intomultiple named files. This is useful when the caller has concatenated a setof Rmd files together (asbookdown does), and those files may need toprocessed by pandoc using the--file-scope option. The firstargument is input file paths and the second isNULL or current filescope which is a named list of files w/name andcontent foreach file. The return is the new file scope. Also, the arguments shouldinclude... for the future extensions.

base_format

An optional format to extend.

Value

An R Markdown output format definition that can be passed torender.

See Also

render,knitr_options,pandoc_options

Examples

## Not run: output_format(knitr = knitr_options(opts_chunk = list(dev = 'png')),              pandoc = pandoc_options(to = "html"))## End(Not run)

Define and merge an R Markdown's output format dependency

Description

Define and merge a dependency such as pre/post-processors from withinchunks. The merge happens explicitly when a list of dependencies arepassed toknitr::knit_meta_add() or implicitly when a dependencyisknitr::knit_printed. Defining a function that does the former isthe best way for package developers to share the dependency. On thecontrary, the latter is useful to declare a document-specific dependency.This function shares some arguments withoutput_format,but lacks the others because dependency is resolved afterpost_knitand beforepre_processor.

Usage

output_format_dependency(  name,  pandoc = list(),  pre_processor = NULL,  post_processor = NULL,  file_scope = NULL,  on_exit = NULL)

Arguments

name

A dependency name. If some dependencies share the same name,then only the first one will be merged to the output format.

pandoc

Pandoc options for an output format (seepandoc_options)

pre_processor

An optional pre-processor function that receives themetadata,input_file,runtime,knit_meta,files_dir, andoutput_dir and can return additional argumentsto pass to pandoc.

post_processor

An optional post-processor function that receives themetadata,input_file,output_file,clean, andverbose parameters, and can return an alternativeoutput_file.

file_scope

A function that will split markdown input to pandoc intomultiple named files. This is useful when the caller has concatenated a setof Rmd files together (asbookdown does), and those files may need toprocessed by pandoc using the--file-scope option. The firstargument is input file paths and the second isNULL or current filescope which is a named list of files w/name andcontent foreach file. The return is the new file scope. Also, the arguments shouldinclude... for the future extensions.

on_exit

A function to call whenrmarkdown::render() finishesexecution (as registered with aon.exit handler).

Value

An list of arguments with the "rmd_dependency" class.

Examples

# Implicitly add lua filters from within a chunk# This relies on (implicit) printing of the dependency in a chunk via# knitr::knit_print()`output_format_dependency(  "lua_filter1",  pandoc = list(lua_filters = "example1.lua"))# Explicitly add lua filters from within a chunkknitr::knit_meta_add(list(output_format_dependency(  "lua_filter2",  pandoc = list(lua_filters = "example2.lua"))))# List the available dependencies# Note that the list may include dependencies with duplicated names. In that# case, the first one is merged to the output format and the others are# discarded.str(knitr::knit_meta("output_format_dependency", clean = FALSE))

The output metadata object

Description

This object provides a mechanism for users to attach metadata as an attribute(namedrmd_output_metadata) of the returned value ofrender(). The initial value of the metadata comes from in thermd_output_metadata field of the YAML frontmatter of an R Markdowndocument. The metadata can be queried via theoutput_metadata$get() method, and modified via theoutput_metadata$set() method.


Create a table in HTML with support for paging rows and columns

Description

Create a table in HTML with support for paging rows and columns

Usage

paged_table(x, options = NULL)

Arguments

x

a data frame to be rendered as a paged table.

options

options for printing the paged table. See details for specifics.

Details

Below are the recognized table pagination options.

Option Description Default
max.print The number of rows to print. 1000
sql.max.print The number of rows to print from a SQL data table. 1000
rows.print The number of rows to display. 10
cols.print The number of columns to display. 10
cols.min.print The minimum number of columns to display. -
pages.print The number of pages to display under page navigation. -
paged.print When set to FALSE turns off paged tables. TRUE
rownames.print When set to FALSE turns off row names. TRUE

Note: There is a hard cap of 10,000 rows to ensure that pandoc will notfail when rendering the document.


Functions for generating pandoc command line arguments

Description

Functions that assist in creating various types of pandoc command linearguments (e.g. for templates, table of contents, highlighting, and contentincludes).

Usage

pandoc_variable_arg(name, value)pandoc_metadata_arg(name, value)pandoc_metadata_file_arg(file)pandoc_include_args(in_header = NULL, before_body = NULL, after_body = NULL)pandoc_highlight_args(highlight, default = "tango")pandoc_latex_engine_args(latex_engine)pandoc_toc_args(toc, toc_depth = 3)pandoc_citeproc_args()pandoc_lua_filter_args(lua_files)

Arguments

name

Name of template variable to set.

value

Value of template variable (defaults totrue if missing).

file

string. Path to a file

in_header

One or more files with content to be included in theheader of the document.

before_body

One or more files with content to be included beforethe document body.

after_body

One or more files with content to be included after thedocument body.

highlight

The name of a pandoc syntax highlighting theme.

default

The highlighting theme to use if "default"is specified.

latex_engine

LaTeX engine for producing PDF output. Options are"pdflatex", "lualatex", "xelatex", and "tectonic".

toc

TRUE to include a table of contents in the output.

toc_depth

Depth of headers to include in table of contents.

lua_files

Character vector of file paths to Lua filter files. Pathswill be transformed bypandoc_path_arg.

Details

Non-absolute paths for resources referenced from thein_header,before_body, andafter_bodyparameters are resolved relative to the directory of the input document.

Value

A character vector with pandoc command line arguments.

About Pandoc citeproc

For Pandoc version before 2.11, a pandoc filter ‘⁠pandoc-citeproc⁠’ isused. Since Pandoc 2.11, the feature is built-in and activated using‘⁠--citeproc⁠’ flag. ‘⁠pandoc_citeproc_arg⁠’ will return the correctswitches depending on the Pandoc version in use.

Examples

## Not run: library(rmarkdown)pandoc_include_args(before_body = "header.htm")pandoc_include_args(before_body = "header.tex")pandoc_highlight_args("kate")pandoc_latex_engine_args("pdflatex")pandoc_toc_args(toc = TRUE, toc_depth = 2)## End(Not run)

Check pandoc availability and version

Description

Determine whether pandoc is currently available on the system (optionallychecking for a specific version or greater). Determine the specific versionof pandoc available.

Usage

pandoc_available(version = NULL, error = FALSE)pandoc_version()

Arguments

version

Required version of pandoc

error

Whether to signal an error if pandoc with the required versionis not found

Details

The system environment variable ‘⁠PATH⁠’ as well as the version of pandocshipped with RStudio (its location is set via the environment variable‘⁠RSTUDIO_PANDOC⁠’ by RStudio products like the RStudio IDE, RStudioServer, Shiny Server, and RStudio Connect, etc) are scanned for pandoc andthe highest version available is used. Please do not modify the environmentvariable ‘⁠RSTUDIO_PANDOC⁠’ unless you know what it means.

Value

pandoc_available returns a logical indicating whether therequired version of pandoc is available.pandoc_version returns anumeric_version with the version of pandoc found.

Examples

## Not run: library(rmarkdown)if (pandoc_available())  cat("pandoc", as.character(pandoc_version()), "is available!\n")if (pandoc_available("1.12.3"))  cat("required version of pandoc is available!\n")## End(Not run)

Convert a bibliograpy file

Description

Convert a bibliography file (e.g. a BibTeX file) to an R list, JSON text,or YAML text

Usage

pandoc_citeproc_convert(file, type = c("list", "json", "yaml"))

Arguments

file

Bibliography file

type

Conversion type

Value

For 'type = "list"', and R list. For 'type = "json"' or 'type = "yaml"',a character vector with the specified format.


Convert a document with pandoc

Description

Convert documents to and from various formats using the pandoc utility.

Usage

pandoc_convert(  input,  to = NULL,  from = NULL,  output = NULL,  citeproc = FALSE,  options = NULL,  verbose = FALSE,  wd = NULL)

Arguments

input

Character vector containing paths to input files(files must be UTF-8 encoded)

to

Format to convert to (if not specified, you must specifyoutput)

from

Format to convert from (if not specified then the format isdetermined based on the file extension ofinput).

output

Output file (if not specified then determined based on formatbeing converted to).

citeproc

TRUE to run the pandoc-citeproc filter (for processingcitations) as part of the conversion.

options

Character vector of command line options to pass to pandoc.

verbose

TRUE to show the pandoc command line which was executed

wd

Working directory in which code will be executed. If notsupplied, defaults to the common base directory ofinput.

Details

Supported input and output formats are described in thepandoc user guide.

The system path as well as the version of pandoc shipped with RStudio (ifrunning under RStudio) are scanned for pandoc and the highest versionavailable is used.

Examples

## Not run: library(rmarkdown)# convert markdown to various formatspandoc_convert("input.md", to = "html")pandoc_convert("input.md", to = "latex")# process citationspandoc_convert("input.md", to = "html", citeproc = TRUE)# add some pandoc optionspandoc_convert("input.md", to = "latex", options = c("--listings"))## End(Not run)

Get the path of the pandoc executable

Description

Returns the path of the pandoc executable used by functions in the thermarkdown package. This is the most recent version of pandoc found ineither the system path or shipped with RStudio.

Usage

pandoc_exec()

Details

See thepandoc manualfor pandoc commands.


Pandoc options for an output format

Description

Define the pandoc options for an R Markdown output format.

Usage

pandoc_options(  to,  from = rmarkdown_format(),  args = NULL,  keep_tex = FALSE,  latex_engine = c("pdflatex", "lualatex", "xelatex", "tectonic"),  ext = NULL,  lua_filters = NULL,  convert_fun = NULL)

Arguments

to

Pandoc format to convert to

from

Pandoc format to convert from

args

Character vector of command line arguments to pass to pandoc

keep_tex

Keep the intermediate tex file used in the conversion to PDF(applies only to 'latex' and 'beamer' target formats)

latex_engine

LaTeX engine to producing PDF output (applies only to'latex' and 'beamer' target formats)

ext

File extension (e.g. ".tex") for output file (ifNULLchooses default based onto). This is typically used to force thefinal output of a latex or beamer conversion to be.tex rather than.pdf.

lua_filters

Character vector of file paths to Lua filters to use withthis format. They will be added to pandoc command line call using--lua-filter argument. Seevignette("lua-filters", package ="rmarkdown") to know more about Lua filters.

convert_fun

A function to convert the input file to the desired outputformat inrender(). If not provided,pandoc_convert() will be used. If a custom function isprovided, its arguments and returned value should match thepandoc_convert() function. Note that this function does not have touse Pandoc but can also use other tools such ascommonmark.

Details

Thefrom argument should be used very cautiously as it's important forusers to be able to rely on a stable definition of supported markdownextensions.

Value

An list that can be passed as thepandoc argument of theoutput_format function.

See Also

output_format,rmarkdown_format


Transform path for passing to pandoc

Description

Transform a path for passing to pandoc on the command line. Callspath.expand on all platforms. On Windows,transform it to a short path name if it contains spaces, and then convertforward slashes to back slashes (as required by pandoc for some pathreferences).

Usage

pandoc_path_arg(path, backslash = TRUE)

Arguments

path

Path to transform

backslash

Whether to replace forward slashes inpath withbackslashes on Windows.

Value

Transformed path that can be passed to pandoc on the command line.


Create a self-contained HTML document using pandoc.

Description

Create a self-contained HTML document by base64 encoding images,scripts, and stylesheets referred by the input document.

Usage

pandoc_self_contained_html(input, output)

Arguments

input

Input html file to create self-contained version of.

output

Path to save output.

Value

(Invisibly) The path of the generated file.


Render a pandoc template.

Description

Use the pandoc templating engine to render a text file. Substitutions aredone using themetadata list passed to the function.

Usage

pandoc_template(metadata, template, output, verbose = FALSE)

Arguments

metadata

A named list containing metadata to pass to template.

template

Path to a pandoc template.

output

Path to save output.

verbose

TRUE to show the pandoc command line which wasexecuted.

Value

(Invisibly) The path of the generated file.


Parse an HTML Notebook

Description

Parse an HTML notebook, retrieving annotation informationrelated to generated outputs in the document, as well as theoriginal R Markdown source document.

Usage

parse_html_notebook(path)

Arguments

path

The path to an R Notebook file (with extension.nb.html).

Details

See theonlinedocumentation for additional details on using thehtml_notebookformat.


Convert to a PDF/LaTeX document

Description

Formats for converting from R Markdown to a PDF or LaTeX document.

Usage

pdf_document(  toc = FALSE,  toc_depth = 2,  number_sections = FALSE,  fig_width = 6.5,  fig_height = 4.5,  fig_crop = "auto",  fig_caption = TRUE,  dev = "pdf",  df_print = "default",  highlight = "default",  template = "default",  keep_tex = FALSE,  keep_md = FALSE,  latex_engine = "pdflatex",  citation_package = c("default", "natbib", "biblatex"),  includes = NULL,  md_extensions = NULL,  output_extensions = NULL,  pandoc_args = NULL,  extra_dependencies = NULL)latex_document(...)latex_fragment(...)

Arguments

toc

TRUE to include a table of contents in the output

toc_depth

Depth of headers to include in table of contents

number_sections

TRUE to number section headings

fig_width

Default width (in inches) for figures

fig_height

Default height (in inches) for figures

fig_crop

Whether to crop PDF figures with the commandpdfcrop. This requires the toolspdfcrop andghostscript to be installed. By default,fig_crop = TRUEif these two tools are available.

fig_caption

TRUE to render figures with captions

dev

Graphics device to use for figure output (defaults to pdf)

df_print

Method to be used for printing data frames. Valid valuesinclude "default", "kable", "tibble", and "paged". The "default" methoduses a corresponding S3 method ofprint, typicallyprint.data.frame. The "kable" method uses theknitr::kable function. The "tibble" method usesthetibble package to print a summary of the data frame. The "paged"method creates a paginated HTML table (note that this method is only validfor formats that produce HTML). In addition to the named methods you canalso pass an arbitrary function to be used for printing data frames. Youcan disable thedf_print behavior entirely by setting the optionrmarkdown.df_print toFALSE. SeeDataframe printing section in bookdown book for examples.

highlight

Syntax highlighting style passed to Pandoc.

Supported built-in styles include "default", "tango", "pygments", "kate","monochrome", "espresso", "zenburn", "haddock", and "breezedark".

Two custom styles are also included, "arrow", an accessible color scheme,and "rstudio", which mimics the default IDE theme. Alternatively, supply apath to a ‘⁠.theme⁠’ file to usea custom Pandocstyle. Note that custom theme requires Pandoc 2.0+.

PassNULL to prevent syntax highlighting.

template

Pandoc template to use for rendering. Pass "default" to usethe rmarkdown package default template; passNULL to use pandoc'sbuilt-in template; pass a path to use a custom template that you'vecreated. See the documentation onpandoc online documentation fordetails on creating custom templates.

keep_tex

Keep the intermediate tex file used in the conversion to PDF.Note that this argument does not control whether to keep the auxiliaryfiles (e.g., ‘.aux’) generated by LaTeX when compiling ‘.tex’ to‘.pdf’. To keep these files, you may setoptions(tinytex.clean =FALSE).

keep_md

Keep the markdown file generated by knitting.

latex_engine

LaTeX engine for producing PDF output. Options are"pdflatex", "lualatex", "xelatex" and "tectonic".

citation_package

The LaTeX package to process citations,natbiborbiblatex. Usedefault if neither package is to be used,which means citations will be processed via the commandpandoc-citeproc.

includes

Named list of additional content to include within thedocument (typically created using theincludes function).

md_extensions

Markdown extensions to be added or removed from thedefault definition of R Markdown. See thermarkdown_format foradditional details.

output_extensions

Pandoc extensions to be added or removed from theoutput format, e.g.,"-smart" means the output format will belatex-smart.

pandoc_args

Additional command line options to pass to pandoc

extra_dependencies

A LaTeX dependencylatex_dependency(), alist of LaTeX dependencies, a character vector of LaTeX package names (e.g.c("framed", "hyperref")), or a named list of LaTeX package optionswith the names being package names (e.g.list(hyperef =c("unicode=true", "breaklinks=true"), lmodern = NULL)). It can be used toadd custom LaTeX packages to the .tex header.

...

Arguments passed topdf_document().

Details

See theonlinedocumentation for additional details on using thepdf_documentformat.

Creating PDF output from R Markdown requires that LaTeX be installed.

R Markdown documents can have optional metadata that is used to generate adocument header that includes the title, author, and date. For more detailssee the documentation on R Markdownmetadata.

R Markdown documents also support citations. You can find more information onthe markdown syntax for citations in theBibliographiesand Citations article in the online documentation.

Many aspects of the LaTeX template used to create PDF documents can becustomized using metadata. For example:

---
title: "Crop Analysis Q3 2013"
fontsize: 11pt
geometry: margin=1in
---

Available metadata variables include:

lang

Document language code (e.g. "es", "fr", "pt-BR")

fontsize

Font size (e.g. 10pt, 11pt, 12pt)

documentclass

LaTeX document class (e.g. article)

classoption

Option fordocumentclass (e.g. oneside); may be repeated

geometry

Options for geometry class (e.g. margin=1in); may be repeated

mainfont, sansfont, monofont, mathfont

Document fonts (works only with xelatex and lualatex, see thelatex_engine option)

linkcolor, urlcolor, citecolor

Color for internal, external, and citation links (red, green, magenta, cyan, blue, black)

linestretch

Options for line spacing (e.g. 1, 1.5, 3)

Value

R Markdown output format to pass torender

Examples

## Not run: library(rmarkdown)# simple invocationrender("input.Rmd", pdf_document())# specify an option for latex enginerender("input.Rmd", pdf_document(latex_engine = "lualatex"))# add a table of contents and pass an option to pandocrender("input.Rmd", pdf_document(toc = TRUE, "--listings"))## End(Not run)

Get the full paths of Lua filters in an R package

Description

Lua filters stored in a source package in the ‘inst/rmarkdown/lua’directory will be installed to the ‘rmarkdown/lua’ directory in thepackage path. This function finds the full paths of the Lua filters in theinstalled packages.

Usage

pkg_file_lua(filters = NULL, package = "rmarkdown")

Arguments

filters

A character vector of filenames for Lua filters to beretrieved in ‘rmarkdown/lua’ folder of the package. By default(NULL), if none is provided, it returns all filters in that folder.

package

The name of the package in which to look for the filters.

Value

A character vector of absolute file paths for the Lua filter from thepackage. The returned paths have been processed bypandoc_path_arg(), so they are ready to be used by Pandoc.

Examples

# list all Lua filters stored in the rmarkdown packagepkg_file_lua()# get a specific filterpkg_file_lua(c("pagebreak.lua", "latex_div.lua"))

Convert to a PowerPoint presentation

Description

Format for converting from R Markdown to a PowerPoint presentation. Pandocv2.0.5 or above is required.

Usage

powerpoint_presentation(  toc = FALSE,  toc_depth = 2,  number_sections = FALSE,  incremental = FALSE,  fig_width = 5,  fig_height = 4,  fig_caption = TRUE,  df_print = "default",  keep_md = FALSE,  md_extensions = NULL,  slide_level = NULL,  reference_doc = "default",  pandoc_args = NULL)

Arguments

toc

TRUE to include a table of contents in the output

toc_depth

Depth of headers to include in table of contents

number_sections

TRUE to number section headings

incremental

TRUE to render slide bullets incrementally. Notethat if you want to reverse the default incremental behavior for anindividual bullet you can precede it with>. For example:⁠> - Bullet Text⁠. See more inPandoc's Manual

fig_width

Default width (in inches) for figures

fig_height

Default height (in inches) for figures

fig_caption

TRUE to render figures with captions

df_print

Method to be used for printing data frames. Valid valuesinclude "default", "kable", "tibble", and "paged". The "default" methoduses a corresponding S3 method ofprint, typicallyprint.data.frame. The "kable" method uses theknitr::kable function. The "tibble" method usesthetibble package to print a summary of the data frame. The "paged"method creates a paginated HTML table (note that this method is only validfor formats that produce HTML). In addition to the named methods you canalso pass an arbitrary function to be used for printing data frames. Youcan disable thedf_print behavior entirely by setting the optionrmarkdown.df_print toFALSE. SeeDataframe printing section in bookdown book for examples.

keep_md

Keep the markdown file generated by knitting.

md_extensions

Markdown extensions to be added or removed from thedefault definition of R Markdown. See thermarkdown_format foradditional details.

slide_level

The heading level which defines individual slides. Bydefault this is the highest header level in the hierarchy that is followedimmediately by content, and not another header, somewhere in the document.This default can be overridden by specifying an explicitslide_level.

reference_doc

Path to a PowerPoint template.

pandoc_args

Additional command line options to pass to pandoc

Value

R Markdown output format to pass torender()


Publish an R Markdown Website

Description

Publish a website to RStudio Connect

Usage

publish_site(  site_dir = ".",  site_name = NULL,  method = c("rsconnect"),  server = NULL,  account = NULL,  render = TRUE,  launch_browser = interactive())

Arguments

site_dir

Directory containing website. Defaults to current working directory.

site_name

Name for the site (names must be unique within an account). Defaultsto the 'name' provided by the site generator (or to the name of the site_dir ifthere is no 'name' specified).

method

Publishing method (currently only "rsconnect" is available)

account,server

Uniquely identify a remote server with either youruseraccount, theserver name, or both. If neither are supplied, andthere are multiple options, you'll be prompted to pick one.

Useaccounts() to see the full list of available options.

render

'TRUE' to render the site locally before publishing.

launch_browser

If ‘TRUE', the system’s default web browser will be launchedautomatically after the site is deployed. Defaults to 'TRUE' in interactive sessionsonly.

Examples

## Not run: library(rmarkdown)publish_site()## End(Not run)

Relative path utility function

Description

Given a directory and a file, return a relative path from the directory tothe file, or the unmodified file path if the file does not appear to be inthe directory.

Usage

relative_to(dir, file)

Arguments

dir

Directory

file

File

Value

Relative path from the directory to the file (or the unmodified filepath if the file does not appear to be in the directory).


Render R Markdown

Description

Render the input file to the specified output format using pandoc. If theinput requires knitting thenknit is called priorto pandoc.

Usage

render(  input,  output_format = NULL,  output_file = NULL,  output_dir = NULL,  output_options = NULL,  output_yaml = NULL,  intermediates_dir = NULL,  knit_root_dir = NULL,  runtime = c("auto", "static", "shiny", "shinyrmd", "shiny_prerendered"),  clean = TRUE,  params = NULL,  knit_meta = NULL,  envir = parent.frame(),  run_pandoc = TRUE,  quiet = FALSE,  encoding = "UTF-8")

Arguments

input

The input file to be rendered. This can be an R script (.R),an R Markdown document (.Rmd), or a plain markdown document.

output_format

The R Markdown output format to convert to. The option"all" will render all formats defined within the file. The option canbe the name of a format (e.g."html_document") and that will renderthe document to that single format. One can also use a vector of formatnames to render to multiple formats. Alternatively, you can pass an outputformat object (e.g.html_document()). If usingNULL then theoutput format is the first one defined in the YAML frontmatter in the inputfile (this defaults to HTML if no format is specified there).If you pass an output format object tooutput_format, the optionsspecified in the YAML header or_output.yml will be ignored and youmust explicitly set all the options you want when you construct the object.If you pass a string, the output format will use the output parameters inthe YAML header or_output.yml.

output_file

The name of the output file. If usingNULL then theoutput filename will be based on filename for the input file. If a filenameis provided, a path to the output file can also be provided. Note that theoutput_dir option allows for specifying the output file path as well,however, if also specifying the path, the directory must exist. Ifoutput_file is specified but does not have a file extension, anextension will be automatically added according to the output format. Toavoid the automatic file extension, put theoutput_file value inI(), e.g.,I('my-output').

output_dir

The output directory for the renderedoutput_file.This allows for a choice of an alternate directory to which the output fileshould be written (the default output directory of that of the input file).If a path is provided with a filename inoutput_file the directoryspecified here will take precedence. Please note that any directory pathprovided will create any necessary directories if they do not exist.

output_options

List of output options that can override the optionsspecified in metadata (e.g. could be used to forceself_contained ormathjax = "local"). Note that this is only valid when the outputformat is read from metadata (i.e. not a custom format object passed tooutput_format).

output_yaml

Paths to YAML files specifying output formats and theirconfigurations. The first existing one is used. If none are found, thenthe function searches YAML files specified to theoutput_yaml top-levelparameter in the YAML front matter, _output.yml or _output.yaml, and then usesthe first existing one.

intermediates_dir

Intermediate files directory. If a path is specifiedthen intermediate files will be written to that path. IfNULL,intermediate files are written to the same directory as the input file.

knit_root_dir

The working directory in which to knit the document;uses knitr'sroot.dir knit option. IfNULL then the behaviorwill follow the knitr default, which is to use the parent directory of thedocument.

runtime

The runtime target for rendering. Thestatic optionproduces output intended for static files;shiny produces outputsuitable for use in a Shiny document (seerun). The default,auto, allows theruntime target specified in the YAML metadatato take precedence, and renders for astatic runtime target otherwise.

clean

UsingTRUE will clean intermediate files that are createdduring rendering.

params

A list of named parameters that override custom paramsspecified within the YAML front-matter (e.g. specifying a dataset to read ora date range to confine output to). Pass"ask" to start anapplication that helps guide parameter configuration.

knit_meta

(This option is reserved for expert use.) Metadatagenerated byknitr.

envir

The environment in which the code chunks are to be evaluatedduring knitting (can usenew.env() to guarantee an empty newenvironment).

run_pandoc

An option for whether to run pandoc to convert Markdownoutput.

quiet

An option to suppress printing during rendering from knitr,pandoc command line and others. To only suppress printing of the last"Output created: " message, you can setrmarkdown.render.message toFALSE

encoding

Ignored. The encoding is always assumed to be UTF-8.

Details

Note that theknitrerror option is set toFALSE duringrendering (which is different from theknitr default value ofTRUE).

For additional details on rendering R scripts seeCompiling R scripts to a notebook.

If nooutput_format parameter is specified then the output format isread from the YAML front-matter of the input file. For example, thefollowing YAML would yield a PDF document:

output: pdf_document

Additional format options can also be specified in metadata. For example:

output:  pdf_document:    toc: true    highlight: zenburn

Multiple formats can be specified in metadata. If nooutput_formatis passed torender then the first one defined will be used:

output:  pdf_document:    toc: true    highlight: zenburn  html_document:    toc: true    theme: united

Formats specified in metadata can be any one of the built in formats (e.g.html_document,pdf_document) or a format definedin another package (e.g.pkg::custom_format).

If there is no format defined in the YAML thenhtml_document will be used.

Value

Whenrun_pandoc = TRUE, the compiled document is written intothe output file, and the path of the output file is returned. Whenrun_pandoc = FALSE, the path of the Markdown output file, withattributesknit_meta (theknitr meta data collected from codechunks) andintermediates (the intermediate files/directoriesgenerated byrender()).

R Markdown

R Markdown supports all of the base pandoc markdown features as well as someoptional features for compatibility with GitHub Flavored Markdown (whichprevious versions of R Markdown were based on). Seermarkdown_format for details.

See Also

knit,output_format,https://pandoc.org

Examples

## Not run: library(rmarkdown)# Render the default (first) format defined in the filerender("input.Rmd")# Render all formats defined in the filerender("input.Rmd", "all")# Render a single format, using parameters for \code{html_document} from# the YAML header parameters.render("input.Rmd", "html_document")# Render a single format, ignoring parameters for \code{html_document} in# the YAML header. Any parameters not passed as arguments to# \code{html_document()} will be assigned to their default values, regardless# of anything in the YAML headerrender("input.Rmd", html_document(toc = TRUE, toc_depth = 2))# Render multiple formatsrender("input.Rmd", c("html_document", "pdf_document"))## End(Not run)

Delay Rendering for an Expression

Description

In a Shiny document, evaluate the given expression after the document hasfinished rendering, instead of during render.

Usage

render_delayed(expr)

Arguments

expr

The expression to evaluate.

Details

This function is useful inside Shiny documents. It delays theevaluation of its argument until the document has finished its initialrender, so that the document can be viewed before the calculation isfinished.

Any expression that returns HTML can be wrapped inrender_delayed.

Value

An object representing the expression.

Note

expr is evaluated in acopy of the environment in whichtherender_delayed call appears. Consequently, no side effectscreated byexpr are visible in succeeding expressions, nor arechanges to the environment after the call torender_delayed visibletoexpr.

expr must be an expression that produces HTML.

Examples

## Not run: # Add the following code to an R Markdown documentdiv(Sys.time())render_delayed({ Sys.sleep(3)      # simulate an expensive computation div(Sys.time())})div(Sys.time())## End(Not run)

Render multiple documents as a website

Description

Render all of the R Markdown documents within a directory as a website.

Usage

render_site(  input = ".",  output_format = "all",  envir = parent.frame(),  quiet = FALSE,  encoding = "UTF-8")clean_site(input = ".", preview = TRUE, quiet = FALSE, encoding = "UTF-8")site_generator(input = ".", output_format = NULL)site_config(input = ".", encoding = "UTF-8")default_site_generator(input, output_format_filter = NULL, ...)

Arguments

input

Website directory (or the name of a file within the directory).

output_format

R Markdown format to convert to (defaults to "all").

envir

The environment in which the code chunks are to be evaluatedduring knitting (can usenew.env to guarantee an empty newenvironment).

quiet

TRUE to suppress messages and other output.

encoding

Ignored. The encoding is always assumed to be UTF-8.

preview

Whether to list the files to be removed rather than actuallyremoving them. Defaulting to TRUE to prevent removing without notice.

output_format_filter

An optional function which is passed theinput file and the output format, and which returns a (potentiallymodified) output format.

...

Currently unused.

Details

Therender_site function enables you to render a collection ofmarkdown documents within a directory as a website. There are tworequirements for a directory to be rendered as a website:

  1. It must contain either an "index.Rmd" or "index.md" file.

  2. It must contain a site configuration file ("_site.yml").

The most minimal valid website is an empty "index.Rmd" and an empty"_site.yml". With this configuration a single empty webpage would begenerated via a call torender_site. If you add additional markdowndocuments to the directory they will also be rendered. By default a site isrendered in the following fashion:

  1. R Markdown (.Rmd) and plain markdown (.md) files in the rootdirectory are rendered. Note however that markdown files beginning with "_"are not rendered (this is a convention to designate files that are includedby top level documents).

  2. All output and supporting files are copied to a "_site" subdirectoryof the website directory (this is configurable, see discussion below).

  3. The following files arenot copied to the "_site"sub-directory:

    • Files beginning with "." (hidden files).

    • Files beginning with "_"

    • Files known to contain R source code (e.g. ".R", ".s", ".Rmd"), Rdata (e.g. ".RData", ".rds"), configuration data (e.g. ".Rproj","rsconnect") or package project management data (e.g."packrat", "renv").

    Note that you can override which files are included or excluded viasettings in "_site.yml" (described below).

  4. Normally R Markdown renders documents as self-contained HTML.However,render_site ensures that dependencies (e.g. CSS,JavaScript, images, etc.) remain in external files. CSS/JavaScriptlibraries are copied to a "site_libs" sub-directory and plots/images arecopied to "_files" sub-directories.

You can remove the files generated byrender_site using theclean_site function.

Value

render_site returns the name of the site output file (relativeto the input directory).clean_site returns the names of thegenerated files removed during cleaning.site_config returns thecontents of _site.yml as an R list.default_site_generator returnsthe default site generator for R Markdown websites.

Configuration

A "_site.yml" file can be used to configure the behavior of site generation.Here is an example configuration file:

name: my-websiteoutput_dir: _siteinclude: ["demo.R"]exclude: ["docs.txt", "*.csv"]navbar:  title: "My Website"  left:    - text: "Home"      href: index.html    - text: "About"      href: about.htmloutput:  html_document:    toc: true    highlight: textmate

Thename field provides a suggested URL path for your website when itis published (by default this is just the name of the directory containingthe site). Theoutput_dir indicates which directory to copy sitecontent into ("_site" is the default if none is specified). Note that thiscan be "." to keep all content within the root website directory alongsidethe source code.

Theinclude andexclude fields enable you to override thedefault behavior vis-a-vis what files are copied into the "_site" directory(wildcards can be used as in the above example).

Thenavbar field can be used to define a navigation bar for websitesbased on thehtml_document format.

Finally, theoutput field enables you to specify output options thatare common to all documents within the website (you can also still providelocal options within each document that override any common options).

new_session: true causes each file to be rendered in a new R session.This prevents the masking problem that arises when different files usefunctions from different packages (namespaces) that share a common name, suchashere::here andlubridate::here ordplyr::filter andMASS::filter. The default behaviour ofrender_site is to use acommon R session.

autospin: true causes.R files to be spinned and rendered(as well as.Rmd files). Ifautospin is set to false (the default),.R files will not be spinned nor rendered.autospin can alsoenumerate a list of .R files to be spinned and rendered.

Custom Site Generation

The behavior of the default site generation function(rmarkdown::default_site) is described above. It is also possible todefine a custom site generator that has alternate behavior. A site generatoris an R function that is bound to by including it in the "site:" field of the"index.Rmd" or "index.md" file. For example:

title: "My Book"output: bookdown::gitbooksite: bookdown::bookdown_site

A site generation function should return a list with the following elements:

name:

The name for the website (e.g. the parent directoryname).

output_dir:

The directory where the website output is writtento. This path should be relative to the site directory (e.g. "." or"_site")

render:

An R function that can be called to generate thesite. The function should accept theinput_file,output_format,envir, andquiet arguments.

clean:

An R function that returns relative paths to the filesgenerated byrender_site (these files are the ones which will beremoved by theclean_site function.

subdirs(optional):

A logical flag that indicates ifthe generator supports nested source files in subdirectories of the project(TRUE) or only at the project root (FALSE). (e.g.blogdown:::blogdown_site())

Note that theinput_file argument will beNULL when the entiresite is being generated. It will be set to a specific file name if afront-end tool is attempting to preview it (e.g. RStudio IDE via the Knitbutton).

Whenquiet = FALSE therender function should also print a lineof output using themessage function indicating which outputfile should be previewed, for example:

if (!quiet)  message("\nOutput created: ", output)

Emitting this line enables front-ends like RStudio to determine which filethey should open to preview the website.

See the source code of thermarkdown::default_site function for aexample of a site generation function.


Render supporting files for an input document

Description

Render (copy) required supporting files for an input document to the_files directory that is associated with the document.

Usage

render_supporting_files(from, files_dir, rename_to = NULL)

Arguments

from

The directory from which the files should be copied.

files_dir

The directory that will receive the copied files.

rename_to

An option to rename the source directory after the copyoperation is complete.

Value

The relative path to the supporting files. This path is suitablefor inclusion in HTMLhref andsrc attributes.


Resolve the output format for an R Markdown document

Description

Read the YAML metadata (and any common output YAML file) for thedocument and return an output format object that can bepassed to therender function.

Usage

resolve_output_format(  input,  output_format = NULL,  output_options = NULL,  output_yaml = NULL)

Arguments

input

Input file (Rmd or plain markdown)

output_format

Name of output format (orNULL to usethe default format for the input file).

output_options

List of output options that should override theoptions specified in metadata.

output_yaml

Paths to YAML files specifying output formats and theirconfigurations. The first existing one is used. If none are found, thenthe function searches YAML files specified to theoutput_yaml top-levelparameter in the YAML front matter, _output.yml or _output.yaml, and then usesthe first existing one.

Details

This function is useful for front-end tools that need to modifythe default behavior of an output format.

Value

An R Markdown output format definition that can be passed torender.


R Markdown input format definition

Description

Compose a pandoc markdown input definition for R Markdownthat can be passed as thefrom argument ofpandoc_options.

Usage

rmarkdown_format(extensions = NULL)from_rmarkdown(implicit_figures = TRUE, extensions = NULL)

Arguments

extensions

Markdown extensions to be added or removed from thedefault definition of R Markdown.

implicit_figures

Automatically make figures from images (defaults toTRUE).

Details

By default R Markdown is defined as all pandoc markdown extensions withthe following tweaks for backward compatibility with the markdown package(+ features are added, - features are removed):

+autolink_bare_uris
+tex_math_single_backslash

For more on pandoc markdown see thepandoc online documentation.

Value

Pandoc markdown format specification

See Also

output_format,pandoc_options

Examples

## Not run: rmarkdown_format("-implicit_figures")## End(Not run)

R Markdown Metadata

Description

Rmd files include a metadata section (typically located at the top of thefile) that can specify (among other things) the title, author, and date ofthe document. Metadata adheres to theYAML formatand is delimited by lines containing three dashes (---). Here is anexample metadata section:

---title: "Crop Analysis Q3 2013"author: Martha Smithdate: October 23rd, 2013---

Note that thetitle field is quoted. This is because titles oftencontained embedded colons (:) and colons followed by a space need tobe quoted in YAML.

Details

When title, author, and date metadata is provided it's used toautomatically create a title section within output documents. If you don'twant this section included in your document then you should remove thecorresponding metadata fields.

When generating PDF and Beamer output there are also a number of othermetadata fields that can be included to customize the appearance and themeof PDF output. For more details see the documentation forpdf_document andbeamer_presentation.


Convert to an RTF document

Description

Format for converting from R Markdown to an RTF document.

Usage

rtf_document(  toc = FALSE,  toc_depth = 3,  number_sections = FALSE,  fig_width = 5,  fig_height = 4,  keep_md = FALSE,  md_extensions = NULL,  pandoc_args = NULL)

Arguments

toc

TRUE to include a table of contents in the output

toc_depth

Depth of headers to include in table of contents

number_sections

TRUE to number section headings

fig_width

Default width (in inches) for figures

fig_height

Default height (in inches) for figures

keep_md

Keep the markdown file generated by knitting.

md_extensions

Markdown extensions to be added or removed from thedefault definition of R Markdown. See thermarkdown_format foradditional details.

pandoc_args

Additional command line options to pass to pandoc

Details

See theonlinedocumentation for additional details on using thertf_document format.

R Markdown documents can have optional metadata that is used to generate adocument header that includes the title, author, and date. For more detailssee the documentation on R Markdownmetadata.

R Markdown documents also support citations. You can find more information onthe markdown syntax for citations in theBibliographiesand Citations article in the online documentation.

Value

R Markdown output format to pass torender

Examples

## Not run: library(rmarkdown)# simple invocationrender("input.Rmd", rtf_document())# specify table of contents optionrender("input.Rmd", rtf_document(toc = TRUE))## End(Not run)

Run a Shiny document

Description

Start a Shiny server for the given document, and render it for display.

Usage

run(  file = "index.Rmd",  dir = dirname(file),  default_file = NULL,  auto_reload = TRUE,  shiny_args = NULL,  render_args = NULL)

Arguments

file

Path to the R Markdown document to launch in a web browser.Defaults toindex.Rmd in the current working directory, but may beNULL to skip launching a browser.

dir

The directory from which to to read input documents. Defaults tothe parent directory offile.

default_file

The file to serve at the Shiny server's root URL. IfNULL (the default), a sensible default is chosen (see Details)

auto_reload

IfTRUE (the default), automatically reload theShiny application when the file currently being viewed is changed on disk.

shiny_args

Additional arguments torunApp.

render_args

Additional arguments torender.

Details

Therun function runs a Shiny document by starting a Shinyserver associated with the document. Theshiny_args parameter can beused to configure the server; see therunAppdocumentation for details.

Once the server is started, the document will be rendered usingrender. The server will initiate a render of the documentwhenever necessary, so it is not necessary to callrun every timethe document changes: ifauto_reload isTRUE, saving thedocument will trigger a render. You can also manually trigger a render byreloading the document in a Web browser.

The server will render any R Markdown (.Rmd) document indir;thefile argument specifies only the initial document to berendered and viewed. You can therefore link to other documents in thedirectory using standard Markdown syntax, e.g.[Analysis Page 2](page2.Rmd).

Ifdefault_file is not specified, nor is a file specified on theURL, then the default document to serve at/ is chosen from (inorder of preference):

If you wish to share R code between your documents, place it in a filenamedglobal.R indir; it will be sourced into the globalenvironment.

Value

Invisible NULL.

Note

Unlikerender,run does not render the document toa file on disk. In most cases a Web browser will be started automaticallyto view the document; seelaunch.browser in therunApp documentation for details.

When using an external web browser with the server, specify the name of theR Markdown file to view in the URL (e.g.http://127.0.0.1:1234/foo.Rmd). A URL without a filename will showthedefault_file as described above.

Examples

## Not run: # Run the Shiny document "index.Rmd" in the current directoryrmarkdown::run()# Run the Shiny document "shiny_doc.Rmd" on port 8241rmarkdown::run("shiny_doc.Rmd", shiny_args = list(port = 8241))## End(Not run)

Add code to a shiny_prerendered context

Description

Programmatic equivalent to including a code chunk with acontext in a runtime: shiny_prerendered document.

Usage

shiny_prerendered_chunk(context, code, singleton = FALSE)

Arguments

context

Context name (e.g. "server", "server-start")

code

Character vector with code

singleton

Collapse multiple identical versions of thischunk into a single chunk.


Clean prerendered content for the specified Rmd input file

Description

Remove the associated html file and supporting _files directoryfor a shiny_prerendered documet.

Usage

shiny_prerendered_clean(input)

Arguments

input

Rmd input file to clean content for


Get the server startup code for a shiny_prerendered server instance

Description

Get the server startup code for a shiny_prerendered server instance

Usage

shiny_prerendered_server_start_code(server_envir)

Arguments

server_envir

Shiny server environment to get code for


Determine website resource files for a directory

Description

Determine which files within a given directory should be copied inorder to serve a website from the directory. Attempts to automaticallyexclude source, data, hidden, and other files not required to servewebsite content.

Usage

site_resources(site_dir, include = NULL, exclude = NULL, recursive = FALSE)

Arguments

site_dir

Site directory to analyze

include

Additional files to include (glob wildcards supported)

exclude

Files to exclude (glob wildcards supported)

recursive

TRUE to return a full recursive file listing;FALSE to just provide top-level files and directories.

Value

Character vector of files and directories to copy


Convert to a slidy presentation

Description

Format for converting from R Markdown to a slidy presentation.

Usage

slidy_presentation(  number_sections = FALSE,  incremental = FALSE,  slide_level = NULL,  duration = NULL,  footer = NULL,  font_adjustment = 0,  fig_width = 8,  fig_height = 6,  fig_retina = 2,  fig_caption = TRUE,  dev = "png",  df_print = "default",  self_contained = TRUE,  highlight = "default",  math_method = "default",  mathjax = "default",  template = "default",  css = NULL,  includes = NULL,  keep_md = FALSE,  lib_dir = NULL,  md_extensions = NULL,  pandoc_args = NULL,  extra_dependencies = NULL,  ...)

Arguments

number_sections

TRUE to number section headings

incremental

TRUE to render slide bullets incrementally. Notethat if you want to reverse the default incremental behavior for anindividual bullet you can precede it with>. For example:⁠> - Bullet Text⁠. See more inPandoc's Manual

slide_level

The heading level which defines individual slides. Bydefault this is the highest header level in the hierarchy that is followedimmediately by content, and not another header, somewhere in the document.This default can be overridden by specifying an explicitslide_level.

duration

Duration (in minutes) of the slide deck. This value is usedto add a countdown timer to the slide footer.

footer

Footer text (e.g. organization name and/or copyright)

font_adjustment

Increase or decrease the default font size (e.g. -1 or+1). You can also manually adjust the font size during the presentationusing the 'S' (smaller) and 'B' (bigger) keys.

fig_width

Default width (in inches) for figures

fig_height

Default height (in inches) for figures

fig_retina

Scaling to perform for retina displays (defaults to 2, whichcurrently works for all widely used retina displays). Set toNULL toprevent retina scaling. Note that this will always beNULL whenkeep_md is specified (this is becausefig_retina relies onoutputting HTML directly into the markdown document).

fig_caption

TRUE to render figures with captions

dev

Graphics device to use for figure output (defaults to pdf)

df_print

Method to be used for printing data frames. Valid valuesinclude "default", "kable", "tibble", and "paged". The "default" methoduses a corresponding S3 method ofprint, typicallyprint.data.frame. The "kable" method uses theknitr::kable function. The "tibble" method usesthetibble package to print a summary of the data frame. The "paged"method creates a paginated HTML table (note that this method is only validfor formats that produce HTML). In addition to the named methods you canalso pass an arbitrary function to be used for printing data frames. Youcan disable thedf_print behavior entirely by setting the optionrmarkdown.df_print toFALSE. SeeDataframe printing section in bookdown book for examples.

self_contained

Produce a standalone HTML file with no externaldependencies, using data: URIs to incorporate the contents of linkedscripts, stylesheets, images, and videos. Note that even for self containeddocuments MathJax is still loaded externally (this is necessary because ofits size).

highlight

Syntax highlighting style passed to Pandoc.

Supported built-in styles include "default", "tango", "pygments", "kate","monochrome", "espresso", "zenburn", "haddock", and "breezedark".

Two custom styles are also included, "arrow", an accessible color scheme,and "rstudio", which mimics the default IDE theme. Alternatively, supply apath to a ‘⁠.theme⁠’ file to usea custom Pandocstyle. Note that custom theme requires Pandoc 2.0+.

PassNULL to prevent syntax highlighting.

math_method

Math rendering engine to use. This will define the math method to use with Pandoc.

  • It can be a string for the engine, one of "mathjax", "mathml", "webtex", "katex", "gladtex", or "r-katex"or "default" formathjax.

  • It can be a list of

    • engine: one of"mathjax", "mathml", "webtex", "katex", or "gladtex".

    • url: A specific url to use withmathjax,katex orwebtex.Note that forengine = "mathjax",url = "local" will use a local version of MathJax (which iscopied into the output directory).

For example,

output:  html_document:    math_method:      engine: katex      url: https://cdn.jsdelivr.net/npm/katex@0.11.1/dist

SeePandoc's Manual about Math in HTML for the detailsabout Pandoc supported methods.

Usingmath_method = "r-katex" will opt-in server side rendering usingKaTeX thanks tokatex R package. This isuseful compared tomath_method = "katex" to have no JS dependency, only aCSS dependency for styling equation.

mathjax

Include mathjax. The "default" option uses an https URL from aMathJax CDN. The "local" option uses a local version of MathJax (which iscopied into the output directory). You can pass an alternate URL or passNULL to exclude MathJax entirely.

template

Pandoc template to use for rendering. Pass "default" to usethe rmarkdown package default template; passNULL to use pandoc'sbuilt-in template; pass a path to use a custom template that you'vecreated. See the documentation onpandoc online documentation fordetails on creating custom templates.

css

One or more css files to include.

includes

Named list of additional content to include within thedocument (typically created using theincludes function).

keep_md

Keep the markdown file generated by knitting.

lib_dir

Directory to copy dependent HTML libraries (e.g. jquery,bootstrap, etc.) into. By default this will be the name of the document with⁠_files⁠ appended to it.

md_extensions

Markdown extensions to be added or removed from thedefault definition of R Markdown. See thermarkdown_format foradditional details.

pandoc_args

Additional command line options to pass to pandoc

extra_dependencies

A LaTeX dependencylatex_dependency(), alist of LaTeX dependencies, a character vector of LaTeX package names (e.g.c("framed", "hyperref")), or a named list of LaTeX package optionswith the names being package names (e.g.list(hyperef =c("unicode=true", "breaklinks=true"), lmodern = NULL)). It can be used toadd custom LaTeX packages to the .tex header.

...

Additional function arguments to pass to the base R Markdown HTMLoutput formatterhtml_document_base

Details

See theonlinedocumentation for additional details on using theslidy_presentationformat.

For more information on markdown syntax for presentations see thepandoc online documentation.

Value

R Markdown output format to pass torender

Examples

## Not run: library(rmarkdown)# simple invocationrender("pres.Rmd", slidy_presentation())# specify an option for incremental renderingrender("pres.Rmd", slidy_presentation(incremental = TRUE))## End(Not run)

Convert to an MS Word document

Description

Format for converting from R Markdown to an MS Word document.

Usage

word_document(  toc = FALSE,  toc_depth = 3,  number_sections = FALSE,  fig_width = 5,  fig_height = 4,  fig_caption = TRUE,  df_print = "default",  highlight = "default",  reference_docx = "default",  keep_md = FALSE,  md_extensions = NULL,  pandoc_args = NULL)

Arguments

toc

TRUE to include a table of contents in the output

toc_depth

Depth of headers to include in table of contents

number_sections

TRUE to number section headings

fig_width

Default width (in inches) for figures

fig_height

Default height (in inches) for figures

fig_caption

TRUE to render figures with captions

df_print

Method to be used for printing data frames. Valid valuesinclude "default", "kable", "tibble", and "paged". The "default" methoduses a corresponding S3 method ofprint, typicallyprint.data.frame. The "kable" method uses theknitr::kable function. The "tibble" method usesthetibble package to print a summary of the data frame. The "paged"method creates a paginated HTML table (note that this method is only validfor formats that produce HTML). In addition to the named methods you canalso pass an arbitrary function to be used for printing data frames. Youcan disable thedf_print behavior entirely by setting the optionrmarkdown.df_print toFALSE. SeeDataframe printing section in bookdown book for examples.

highlight

Syntax highlighting style passed to Pandoc.

Supported built-in styles include "default", "tango", "pygments", "kate","monochrome", "espresso", "zenburn", "haddock", and "breezedark".

Two custom styles are also included, "arrow", an accessible color scheme,and "rstudio", which mimics the default IDE theme. Alternatively, supply apath to a ‘⁠.theme⁠’ file to usea custom Pandocstyle. Note that custom theme requires Pandoc 2.0+.

PassNULL to prevent syntax highlighting.

reference_docx

Use the specified file as a style reference inproducing a docx file. For best results, the reference docx should be amodified version of a docx file produced using pandoc. Pass "default"to use the rmarkdown default styles.

keep_md

Keep the markdown file generated by knitting.

md_extensions

Markdown extensions to be added or removed from thedefault definition of R Markdown. See thermarkdown_format foradditional details.

pandoc_args

Additional command line options to pass to pandoc

Details

See theonlinedocumentation for additional details on using theword_document format.

R Markdown documents can have optional metadata that is used to generate adocument header that includes the title, author, and date. For more detailssee the documentation on R Markdownmetadata.

R Markdown documents also support citations. You can find more information onthe markdown syntax for citations in theBibliographiesand Citations article in the online documentation.

Value

R Markdown output format to pass torender

Examples

## Not run: library(rmarkdown)# simple invocationrender("input.Rmd", word_document())# specify an option for syntax highlightingrender("input.Rmd", word_document(highlight = "zenburn"))## End(Not run)

Parse the YAML front matter from a file

Description

Parse the YAML front matter from a file

Usage

yaml_front_matter(input, encoding = "UTF-8")

Arguments

input

Input file (Rmd or plain markdown)

encoding

Ignored. The encoding is always assumed to be UTF-8.


[8]ページ先頭

©2009-2025 Movatter.jp