| Type: | Package |
| Title: | A General-Purpose Package for Dynamic Report Generation in R |
| Version: | 1.50 |
| Description: | Provides a general-purpose tool for dynamic report generation in R using Literate Programming techniques. |
| Depends: | R (≥ 3.6.0) |
| Imports: | evaluate (≥ 0.15), highr (≥ 0.11), methods, tools, xfun (≥0.51), yaml (≥ 2.1.19) |
| Suggests: | bslib, codetools, DBI (≥ 0.4-1), digest, formatR, gifski,gridSVG, htmlwidgets (≥ 0.7), jpeg, JuliaCall (≥ 0.11.1),magick, litedown, markdown (≥ 1.3), png, ragg, reticulate (≥1.4), rgl (≥ 0.95.1201), rlang, rmarkdown, sass, showtext,styler (≥ 1.2.0), targets (≥ 0.6.0), testit, tibble,tikzDevice (≥ 0.10), tinytex (≥ 0.56), webshot, rstudioapi,svglite |
| License: | GPL-2 |GPL-3 [expanded from: GPL] |
| URL: | https://yihui.org/knitr/ |
| BugReports: | https://github.com/yihui/knitr/issues |
| Encoding: | UTF-8 |
| VignetteBuilder: | litedown, knitr |
| SystemRequirements: | Package vignettes based on R Markdown v2 orreStructuredText require Pandoc (http://pandoc.org). Thefunction rst2pdf() requires rst2pdf(https://github.com/rst2pdf/rst2pdf). |
| Collate: | 'block.R' 'cache.R' 'citation.R' 'hooks-html.R' 'plot.R''utils.R' 'defaults.R' 'concordance.R' 'engine.R' 'highlight.R''themes.R' 'header.R' 'hooks-asciidoc.R' 'hooks-chunk.R''hooks-extra.R' 'hooks-latex.R' 'hooks-md.R' 'hooks-rst.R''hooks-textile.R' 'hooks.R' 'output.R' 'package.R' 'pandoc.R''params.R' 'parser.R' 'pattern.R' 'rocco.R' 'spin.R' 'table.R''template.R' 'utils-conversion.R' 'utils-rd2html.R''utils-string.R' 'utils-sweave.R' 'utils-upload.R''utils-vignettes.R' 'zzz.R' |
| RoxygenNote: | 7.3.2 |
| NeedsCompilation: | no |
| Packaged: | 2025-03-15 00:17:19 UTC; runner |
| Author: | Yihui Xie |
| Maintainer: | Yihui Xie <xie@yihui.name> |
| Repository: | CRAN |
| Date/Publication: | 2025-03-16 09:20:02 UTC |
A general-purpose tool for dynamic report generation in R
Description
Theknitr package is an implementation of Literate Programming, aprogramming paradigm that intermingle code chunks (for computing) with prose(for documentation) in the same document.
Details
When the document is compiled, the code chunks can be executed, and theresults from computing (text or graphics) are automatically written to theoutput along with the prose.
This package is an alternative tool to Sweave with a more flexible design andnew features like caching and finer control of graphics. It is not limited toLaTeX and is ready to be customized to process other file formats. See thepackage website in the references for more information and examples.
Note
The pronunciation ofknitr is similar toneater or you canthink ofknitter (but it issingle t). The name comes fromknit +R (whileSweave =S +weave).
Author(s)
Yihui Xie <https://yihui.org>
References
Full documentation and demos:https://yihui.org/knitr/;FAQ's:https://yihui.org/knitr/faq/
See Also
The core function in this package:knit. If you are anSweave user, seeSweave2knitr on how to convert Sweave filestoknitr.
Convert Sweave to knitr documents
Description
This function converts an Sweave document to aknitr-compatibledocument.
Usage
Sweave2knitr( file, output = gsub("[.]([^.]+)$", "-knitr.\\1", file), text = NULL)Arguments
file | Path to the Rnw file (must be encoded in UTF-8). |
output | Output file path. By default, ‘file.Rnw’ produces‘file-knitr.Rnw’); if |
text | An alternative way to provide the Sweave code as a characterstring. If |
Details
The pseudo command ‘\SweaveInput{file.Rnw}’ is converted to a codechunk header<<child='file.Rnw'>>=.
Similarly ‘\SweaveOpts{opt = value}’ is converted to a code chunk‘opts_chunk$set(opt = value)’ with the chunk optioninclude =FALSE; the options are automatically fixed in the same way as local chunkoptions (explained below).
The Sweave package ‘\usepackage{Sweave}’ in the preamble is removedbecause it is not required.
Chunk options are updated if necessary: option valuestrue andfalse are changed toTRUE andFALSE respectively;fig=TRUE is removed because it is not necessary forknitr (plotswill be automatically generated);fig=FALSE is changed tofig.keep='none'; the devicespdf/jpeg/png/eps/tikz=TRUE areconverted todev='pdf'/'jpeg'/'png'/'postscript'/'tikz';pdf/jpeg/png/eps/tikz=FALSE are removed;results=tex/verbatim/hide are changed toresults='asis'/'markup'/'hide';width/height are changed tofig.width/fig.height;prefix.string is changed tofig.path;print/term/prefix=TRUE/FALSE are removed; most of thecharacter options (e.g.engine andout.width) are quoted;keep.source=TRUE/FALSE is changed totidy=FALSE/TRUE (note theorder of values).
If a line@ (it closes a chunk) directly follows a previous@, it is removed; if a line@ appears before a code chunk andno chunk is before it, it is also removed, becauseknitr only uses one‘@’ after ‘<<>>=’ by default (which is not the original Nowebsyntax but more natural).
Value
Iftext isNULL, theoutput file is written andNULL is returned. Otherwise, the converted text string is returned.
Note
If ‘\SweaveOpts{}’ spans across multiple lines, it will not befixed, and you have to fix it manually. The LaTeX-style syntax of Sweavechunks are ignored (see?SweaveSyntaxLatex); only the Noweb syntaxis supported.
References
The motivation of the changes in the syntax:https://yihui.org/knitr/demo/sweave/
See Also
Examples
Sweave2knitr(text = "<<echo=TRUE>>=") # this is validSweave2knitr(text = "<<png=true>>=") # dev='png'Sweave2knitr(text = "<<eps=TRUE, pdf=FALSE, results=tex, width=5, prefix.string=foo>>=")Sweave2knitr(text = "<<,png=false,fig=TRUE>>=")Sweave2knitr(text = "\\SweaveOpts{echo=false}")Sweave2knitr(text = "\\SweaveInput{hello.Rnw}")# Sweave example in utilstestfile = system.file("Sweave", "Sweave-test-1.Rnw", package = "utils")Sweave2knitr(testfile, output = "Sweave-test-knitr.Rnw")if (interactive()) knit("Sweave-test-knitr.Rnw") # or knit2pdf() directlyunlink("Sweave-test-knitr.Rnw")Get all chunk labels in a document
Description
The functionall_labels() returns all chunk labels as a charactervector. Optionally, you can specify a series of conditions to filter thelabels. The function 'all_rcpp_labels()' is a wrapper function forall_labels(engine == 'Rcpp').
Usage
all_labels(...)all_rcpp_labels(...)Arguments
... | A vector of R expressions, each of which should return |
Details
For example, suppose the condition expression isengine == 'Rcpp', theobjectengine is the local chunk optionengine. If anexpression fails to be evaluated (e.g. when a certain object does not exist),FALSE is returned and the label for this chunk will be filtered out.
Value
A character vector.
Note
Empty code chunks are always ignored, including those chunks that areempty in the original document but filled with code using chunk optionssuch asref.label orcode.
Examples
# the examples below are meaningless unless you put them in a knitr documentall_labels()all_labels(engine == "Rcpp")all_labels(echo == FALSE && results != "hide")# or separate the two conditionsall_labels(echo == FALSE, results != "hide")All built-in patterns
Description
This object is a named list of all built-in patterns.
Usage
all_patternsFormat
An object of classlist of length 8.
References
Usage:https://yihui.org/knitr/patterns/
See Also
Examples
all_patterns$rnwall_patterns$htmlstr(all_patterns)Mark an R object with a special class
Description
This is a convenience function that assigns the input object a class namedknit_asis, so thatknitr will treat it as is (the effect is thesame as the chunk optionresults = 'asis') when it is written to theoutput.
Usage
asis_output(x, meta = NULL, cacheable = NA)Arguments
x | An R object. Typically a character string, or an object which canbe converted to a character string via |
meta | Additional metadata of the object to be printed. The metadatawill be collected when the object is printed, and accessible via |
cacheable | Boolean indicating whether this object is cacheable. If |
Details
This function is normally used in a custom S3 method based on the printingfunctionknit_print().
For thecacheable argument, you need to be careful when printing theobject involves non-trivial side effects, in which case it is stronglyrecommended to usecacheable = FALSE to instructknitr that thisobject should not be cached using the chunk optioncache = TRUE,otherwise the side effects will be lost the next time the chunk is knitted.For example, printing ashiny input element or an HTML widget in an RMarkdown document may involve registering metadata about some JavaScriptlibraries or stylesheets, and the metadata may be lost if we cache the codechunk, because the code evaluation will be skipped the next time. Thisparticular issue has been solved inknitr after v1.13 (the metadatawill be saved and loaded automatically when caching is enabled), but not allmetadata can be saved and loaded next time and still works in the new Rsession.
Note
This function only works in top-level R expressions, and it will notwork when it is called inside another expression, such as a for-loop. Seehttps://github.com/yihui/knitr/issues/1137 for a discussion.
Examples
# see ?knit_printCache engines of other languages
Description
This object controls how to load cached environments from languages otherthan R (when the chunk optionengine is not'R'). Eachcomponent in this object is a function that takes the current path to thechunk cache and loads it into the language environment.
Usage
cache_enginesFormat
An object of classlist of length 7.
Details
The cache engine function has one argumentoptions, a list containingall chunk options. Note thatoptions$hash is the path to the currentchunk cache with the chunk's hash, but without any file extension, and thelanguage engine may write a cache database to this path (with an extension).
The cache engine function should load the cache environment and should knowthe extension appropriate for the language.
References
Seehttps://github.com/rstudio/reticulate/pull/167 for animplementation of a cache engine for Python.
Clean cache files that are probably no longer needed
Description
If you remove or rename some cached code chunks, their original cache fileswill not be automatically cleaned. You can use this function to identifythese possible files, and clean them if you are sure they are no longerneeded.
Usage
clean_cache(clean = FALSE, path = opts_chunk$get("cache.path"))Arguments
clean | Boolean; whether to remove the files. |
path | Path to the cache. |
Note
The identification is not guaranteed to be correct, especially whenmultiple documents share the same cache directory. You are recommended tocallclean_cache(FALSE) and carefully check the list of files (ifany) before you really delete them (clean_cache(TRUE)).
This function must be called within a code chunk in a source document,since it needs to know all chunk labels of the current document todetermine which labels are no longer present, and delete cachecorresponding to these labels.
Combine multiple words into a single string
Description
This is a wrapper function ofxfun::join_words().
Usage
combine_words(...)Arguments
... | Arguments passed to |
Convert the in-header chunk option syntax to the in-body syntax
Description
This is a helper function for moving chunk options from the chunk header tothe chunk body using the new syntax.
Usage
convert_chunk_header( input, output = NULL, type = c("multiline", "wrap", "yaml"), width = 0.9 * getOption("width"))Arguments
input | File path to the document with code chunks to convert. |
output | The default |
type | This determines how the in-body options will be formatted. |
width | An integer passed to |
Value
A character vector of convertedinput whenoutput = NULL. The output file path with converted content otherwise.
Aboutknitr option syntax
Historical chunk option syntax have chunk option in the chunk header usingvalid R syntax. This is an example for.Rmd document
```{r, echo = FALSE, fig.width: 10}```New syntax allows to pass option inside the chunk using several variants
Passing options one per line using valid R syntax. This corresponds to
convert_chunk_header(type = "multiline").```{r}#| echo = FALSE,#| fig.width = 10```Passing option part from header in-chunk with several line if wrapping isneeded. This corresponds to
convert_chunk_header(type = "wrap")```{r}#| echo = FALSE, fig.width = 10```Passing options key value pairs in-chunk using YAML syntax. Values are nomore R expression but valid YAML syntax. This corresponds to
convert_chunk_header(type = "yaml")(not implement yet).```{r}#| echo: false,#| fig.width: 10```
Note
Learn more about the new chunk option syntax inhttps://yihui.org/en/2022/01/knitr-news/
Examples
knitr_example = function(...) system.file("examples", ..., package = "knitr")# Convert a document for multiline typeconvert_chunk_header(knitr_example("knitr-minimal.Rmd"))# Convert a document for wrap typeconvert_chunk_header(knitr_example("knitr-minimal.Rmd"), type = "wrap")# Reduce default wrapping widthconvert_chunk_header(knitr_example("knitr-minimal.Rmd"), type = "wrap", width = 0.6 * getOption("width"))## Not run: # Explicitly name the outputconvert_chunk_header("test.Rmd", output = "test2.Rmd")# Overwrite the inputconvert_chunk_header("test.Rmd", output = identity)# Use a custom function to name the outputconvert_chunk_header("test.Rmd", output = \(f) sprintf("%s-new.%s", xfun::sans_ext(f), xfun::file_ext(f)))## End(Not run)Query the current input filename
Description
Returns the name of the input file passed toknit().
Usage
current_input(dir = FALSE)Arguments
dir | Boolean; whether to prepend the current working directory to the file path,i.e. whether to return an absolute path or a relative path. |
Value
A character string, if this function is called inside an inputdocument. OtherwiseNULL.
Build automatic dependencies among chunks
Description
When the chunk optionautodep = TRUE, all names of objects created ina chunk will be saved in a file named ‘__objects’ and all global objectsused in a chunk will be saved to ‘__globals’. This function can analyzeobject names in these files to automatically build cache dependencies, whichis similar to the effect of thedependson option. It is supposed to beused in the first chunk of a document and this chunk must not be cached.
Usage
dep_auto(path = opts_chunk$get("cache.path"), labels = all_labels())Arguments
path | Path to the dependency file. |
labels | A vector of labels of chunks for which the dependencies will bebuilt. By default, dependencies for all chunks will be built. |
Value
NULL. The dependencies are built as a side effect.
Note
Be cautious aboutpath: because this function is used in achunk, the working directory when the chunk is evaluated is the directoryof the input document inknit, and if that directory differsfrom the working directory before callingknit(), you need to adjustthepath argument here to make sure this function can find the cachefiles ‘__objects’ and ‘__globals’.
References
https://yihui.org/knitr/demo/cache/
See Also
Make later chunks depend on previous chunks
Description
This function can be used to build dependencies among chunks so that alllater chunks depend on previous chunks, i.e. whenever the cache of a previouschunk is updated, the cache of all its later chunks will be updated.
Usage
dep_prev()Value
NULL; the internal dependency structure is updated as a sideeffect.
References
https://yihui.org/knitr/demo/cache/
See Also
Download an image from the web and include it in a document
Description
When including images in non-HTML output formats such as LaTeX/PDF, URLs willnot work as image paths. In this case, we have to download the images. Thisfunction is a wrapper ofxfun::download_file() andinclude_graphics().
Usage
download_image( url, path = xfun::url_filename(url), use_file = !pandoc_to("html"), ...)Arguments
url | The URL of an image. |
path | The download path (inferred from the URL by default). If the fileexists, it will not be downloaded (downloading can take time and requiresInternet connection). If you are sure the file needs to be downloadedagain, delete it beforehand. |
use_file | Whether to use the URL or the download path to include theimage. By default, the URL is used for HTML output formats, and the filepath is used for other output formats. |
... | Other arguments to be passed to |
Examples
knitr::download_image("https://www.r-project.org/Rlogo.png")An output wrapper for language engine output
Description
If you have designed a language engine, you may call this function in the endto format and return the text output from your engine.
Usage
engine_output(options, code, out, extra = NULL)Arguments
options | A list of chunk options. Usually this is just the object |
code | Source code of the chunk, to which the output hook |
out | Text output from the engine, to which the hook |
extra | Any additional text output that you want to include. |
Details
For expert users, an advanced usage of this function isengine_output(options, out = LIST) whereLIST is a list thathas the same structure as the output ofevaluate::evaluate(). In thiscase, the argumentscode andextra are ignored, and the list ispassed toknitr::sew() to return a character vector of final output.
Value
A character string generated from the source code and output usingthe appropriate output hooks.
Examples
library(knitr)engine_output(opts_chunk$merge(list(engine = "Rscript")), code = "1 + 1", out = "[1] 2")engine_output(opts_chunk$merge(list(echo = FALSE, engine = "Rscript")), code = "1 + 1", out = "[1] 2")# expert use onlyengine_output(opts_chunk$merge(list(engine = "python")), out = list(structure(list(src = "1 + 1"), class = "source"), "2"))Mark character strings as raw output that should not be converted
Description
These functions provide a mechanism to protect the character output of R codechunks. The output is annotated with special markers inraw_output;extract_raw_output() will extract raw output wrapped in the markers,and replace the raw output with its MD5 digest;restore_raw_output()will restore the MD5 digest with the original raw output.
Usage
extract_raw_output(text, markers = raw_markers)restore_raw_output(text, chunks, markers = raw_markers)raw_output(x, markers = raw_markers, ...)Arguments
text | For |
markers | A length-2 character vector to be used to wrap |
chunks | A named character vector returned from |
x | The character vector to be protected. |
... | Arguments to be passed to |
Details
This mechanism is designed primarily for R Markdown pre/post-processors. Inan R code chunk, you generateraw_output() to the Markdown output. Inthe pre-processor, you canextract_raw_output() from the Markdownfile, store the raw output and MD5 digests, and remove the actual raw outputfrom Markdown so Pandoc will never see it. In the post-processor, you canread the Pandoc output (e.g., an HTML or RTF file), and restore the rawoutput.
Value
Forextract_raw_output(), a list of two components:value (thetext with raw output replaced by MD5 digests) andchunks (a named character vector, of which the names are MD5 digestsand values are the raw output). Forrestore_raw_output(), therestoredtext.
Examples
library(knitr)out = c("*hello*", raw_output("<special>content</special> *protect* me!"), "*world*")pre = extract_raw_output(out)str(pre)pre$value = gsub("[*]([^*]+)[*]", "<em>\\1</em>", pre$value) # think this as Pandoc conversionpre$value# raw output was protected from the conversion# (e.g. *protect* was not converted)restore_raw_output(pre$value, pre$chunks)Obtain the figure filenames for a chunk
Description
Given a chunk label, the figure file extension, the figure number(s), and thechunk optionfig.path, return the filename(s).
Usage
fig_chunk(label, ext = "", number, fig.path = opts_chunk$get("fig.path"))Arguments
label | The chunk label. |
ext | The figure file extension, e.g. |
number | The figure number (by default |
fig.path | Passed to |
Details
This function can be used in an inline R expression to write out the figurefilenames without hard-coding them. For example, if you created a plot in acode chunk with the labelfoo and figure path ‘my-figure/’, youare not recommended to use hard-coded figure paths like‘\includegraphics{my-figure/foo-1.pdf}’ (in ‘.Rnw’ documents) or‘’ (R Markdown) in your document. Instead, youshould use ‘\Sexpr{fig_chunk('foo', 'pdf')}’ or ‘`)’.
You can generate plots in a code chunk but not show them inside the codechunk by using the chunk optionfig.show = 'hide'. Then you can usethis function if you want to show them elsewhere.
Value
A character vector of filenames.
Examples
library(knitr)fig_chunk("foo", "png")fig_chunk("foo", "pdf")fig_chunk("foo", "svg", 2) # the second plot of the chunk foofig_chunk("foo", "png", 1:5) # if the chunk foo produced 5 plotsPath for figure files
Description
The filename of figure files is the combination of optionsfig.pathandlabel. This function returns the path of figures for the currentchunk by default.
Usage
fig_path(suffix = "", options = opts_current$get(), number)Arguments
suffix | A filename suffix; if it is non-empty and does notcontain a dot |
options | A list of options; by default the options of the current chunk. |
number | The current figure number. The default is the internal chunk option |
Value
A character vector of the form ‘fig.path-label-i.suffix’.
Note
When there are special characters (not alphanumeric or ‘-’ or‘_’) in the path, they will be automatically replaced with ‘_’.For example, ‘a b/c.d-’ will be sanitized to ‘a_b/c_d-’. Thismakes the filenames safe to LaTeX.
Examples
fig_path(".pdf", options = list(fig.path = "figure/abc-", label = "first-plot"))fig_path(".png", list(fig.path = "foo-", label = "bar"), 1:10)Hooks to create animations in HTML output
Description
hook_ffmpeg_html() uses FFmpeg to convert images to a video;hook_gifski() uses thegifski to convert images to a GIFanimation;hook_scianimator() uses the JavaScript library SciAnimatorto create animations;hook_r2swf() uses theR2SWF package.
Usage
hook_ffmpeg_html(x, options)hook_gifski(x, options)hook_scianimator(x, options)hook_r2swf(x, options)Arguments
x | Filename for the plot (a character string). |
options | A list of the current chunk options. |
Details
These hooks are mainly for the package optionanimation.fun, e.g. youcan setopts_knit$set(animation.fun = hook_scianimator).
Some potentially useful document hooks
Description
A document hook is a function to post-process the output document.
Usage
hook_movecode(x)Arguments
x | A character string (the whole output document). |
Details
hook_movecode() is a document hook to move code chunks out of LaTeXfloating environments like ‘figure’ and ‘table’ when the chunkswere actually written inside the floats. This function is primarily designedfor LyX: we often insert code chunks into floats to generate figures ortables, but in the final output we do not want the code to float with theenvironments, so we use regular expressions to find out the floatingenvironments, extract the code chunks and move them out. To disable thisbehavior, use a comment% knitr_do_not_move in the floatingenvironment.
Value
The post-processed document as a character string.
Note
These functions are hackish. Also notehook_movecode() assumesyou to use the default output hooks for LaTeX (not Sweave or listings), andevery figure/table environment must have a label.
References
https://yihui.org/knitr/hooks/
Examples
## Not run: knit_hooks$set(document = hook_movecode)## End(Not run)# see example 103 at https://github.com/yihui/knitr-examplesBuilt-in chunk hooks to extend knitr
Description
Hook functions are called when the corresponding chunk options are notNULL to do additional jobs beside the R code in chunks. This packageprovides a few useful hooks, which can also serve as examples of how todefine chunk hooks inknitr.
Usage
hook_pdfcrop(before, ...)hook_optipng(...)hook_pngquant(...)hook_mogrify(...)hook_plot_custom(before, options, envir)hook_purl(before, options, ...)Arguments
before,options,envir,... | SeeReferences below. |
Details
The functionhook_pdfcrop() callsplot_crop() to cropthe white margins of PDF plots.
The functionhook_optipng() calls the programoptipng tooptimize PNG images. Note the chunk optionoptipng can be used toprovide additional parameters to the programoptipng, e.g.optipng = '-o7'.
The functionhook_pngquant() calls the programpngquant tooptimize PNG images. Note the chunk optionpngquant can be used toprovide additional parameters to the programpngquant, e.g.pngquant = '--speed=1 --quality=0-50'.
The functionhook_mogrify() calls the programmogrify. Notethe chunk optionmogrify can be used to provide additional parametersto the programmogrify (with default-trim to trim PNGfiles).
When the plots are not recordable viagrDevices::recordPlot()and we save the plots to files manually via other functions (e.g.rglplots), we can use the chunk hookhook_plot_custom to help write codefor graphics output into the output document.
The hookhook_purl() can be used to write the code chunks to an Rscript. It is an alternative approach topurl, and can be morereliable when the code chunks depend on the execution of them (e.g.read_chunk(), oropts_chunk$set(eval = FALSE)).To enable this hook, it is recommended to associate it with the chunk optionpurl, i.e.knit_hooks$set(purl = hook_purl). When this hook isenabled, an R script will be written while the input document is beingknit. Currently the code chunks that are not R code or have thechunk optionpurl=FALSE are ignored. Please note when the cache isturned on (the chunk optioncache = TRUE), no chunk hooks will beexecuted, hencehook_purl() will not work, either. To solve thisproblem, we needcache = 2 instead ofTRUE (seehttps://yihui.org/knitr/demo/cache/ for the meaning ofcache =2).
Note
The two hook functionshook_rgl() andhook_webgl() weremoved fromknitr to thergl package (>= v0.95.1247) afterknitr v1.10.5, and you canlibrary(rgl) to get them.
References
https://yihui.org/knitr/hooks/#chunk-hooks
See Also
rgl::rgl.snapshot,rgl::rgl.postscript,rgl::hook_rgl,rgl::hook_webgl
Examples
if (require("rgl") && exists("hook_rgl")) knit_hooks$set(rgl = hook_rgl)# then in code chunks, use the option rgl=TRUEDefault plot hooks for different output formats
Description
These hook functions define how to mark up graphics output in differentoutput formats.
Usage
hook_plot_html(x, options)hook_plot_asciidoc(x, options)hook_plot_tex(x, options)hook_plot_md(x, options)hook_plot_rst(x, options)hook_plot_textile(x, options)Arguments
x | Filename for the plot (a character string). |
options | A list of the current chunk options. |
Details
Depending on the options passed over,hook_plot_tex may return thenormal ‘\includegraphics{}’ command, or ‘\input{}’ (for tikzfiles), or ‘\animategraphics{}’ (for animations); it also takes manyother options into consideration to align plots and set figure sizes, etc.Similarly,hook_plot_html,hook_plot_md andhook_plot_rst return character strings which are HTML, Markdown, reSTcode.
In most cases we do not need to call these hooks explicitly, and they weredesigned to be used internally. Sometimes we may not be able to record Rplots usinggrDevices::recordPlot(), and we can make use ofthese hooks to insert graphics output in the output document; seehook_plot_custom for details.
Value
A character string of code, with plot filenames wrapped.
References
https://yihui.org/knitr/hooks/
See Also
Examples
# this is what happens for a chunk like this# <<foo-bar-plot, dev='pdf', fig.align='right'>>=hook_plot_tex("foo-bar-plot.pdf", opts_chunk$merge(list(fig.align = "right")))# <<bar, dev='tikz'>>=hook_plot_tex("bar.tikz", opts_chunk$merge(list(dev = "tikz")))# <<foo, dev='pdf', fig.show='animate', interval=.1>>=# 5 plots are generated in this chunkhook_plot_tex("foo5.pdf", opts_chunk$merge(list(fig.show = "animate", interval = 0.1, fig.cur = 5, fig.num = 5)))Encode an image file to a data URI
Description
This function is the same asxfun::base64_uri() (only with adifferent function name). It can encode an image file as a base64 string,which can be used in theimg tag in HTML.
Usage
image_uri(f)Arguments
f | Path to the image file. |
Value
The data URI as a character string.
Author(s)
Wush Wu and Yihui Xie
References
https://en.wikipedia.org/wiki/Data_URI_scheme
Examples
uri = image_uri(file.path(R.home("doc"), "html", "logo.jpg"))if (interactive()) { cat(sprintf("<img src=\"%s\" />", uri), file = "logo.html") browseURL("logo.html") # you can check its HTML source}Upload an image to imgur.com
Description
This function is an alias toxfun::upload_imgur(). It is kept inknitr only for backward-compatibility reasons. You are recommended tousexfun::upload_imgur() directly instead.
Usage
imgur_upload(file, key = xfun::env_option("knitr.imgur.key"), ...)Arguments
file,key,... | See |
Embed external images inknitr documents
Description
When plots are not generated from R code, there is no way forknitr tocapture plots automatically. In this case, you may generate the imagesmanually and pass their file paths to this function to include them in theoutput. The major advantage of using this function is that it is portable inthe sense that it works for all document formats thatknitr supports,so you do not need to think if you have to use, for example, LaTeX orMarkdown syntax, to embed an external image. Chunk options related tographics output that work for normal R plots also work for these images, suchasout.width andout.height.
Usage
include_graphics( path, auto_pdf = getOption("knitr.graphics.auto_pdf", FALSE), dpi = NULL, rel_path = getOption("knitr.graphics.rel_path", TRUE), error = getOption("knitr.graphics.error", TRUE))Arguments
path | A character vector of image paths. Both local file paths and webpaths are supported. Note that the |
auto_pdf | Whether to use PDF images automatically when the outputformat is LaTeX. If |
dpi | DPI (dots per inch) value. Used to calculate the output width (ininches) of the images. This will be their actual width in pixels, dividedby |
rel_path | Whether to automatically convert absolute paths to relativepaths. If you know for sure that absolute paths work, you may set thisargument or the global option |
error | Whether to signal an error if any files specified in the |
Value
The same as the input character vectorpath but it is markedwith special internal S3 classes so thatknitr will convert the filepaths to proper output code according to the output format.
Note
This function is supposed to be used in R code chunks or inline R codeexpressions. For local images, you are recommended to use relative pathswith forward slashes instead of backslashes (e.g., ‘images/fig1.png’instead of ‘/Users/me/code/images/fig1.png’).
The automatic calculation of the output width requires thepngpackage (for PNG images) or thejpeg package (for JPEG images). Thewidth will not be calculated if the chunk optionout.width isalready provided ordpi = NA.
Embed a URL as an HTML iframe or a screenshot inknitr documents
Description
When the output format is HTML,include_url() inserts an iframe in theoutput; otherwise it takes a screenshot of the URL and insert the image inthe output.include_app() takes the URL of a Shiny app and adds‘?showcase=0’ to it (to disable the showcase mode), then passes the URLtoinclude_url().
Usage
include_url(url, height = "400px")include_app(url, height = "400px")Arguments
url | A character vector of URLs. |
height | A character vector to specify the height of iframes. |
Value
An R object with a special class thatknitr recognizesinternally to generate the iframes or screenshots.
See Also
Wrap code using the inline R expression syntax
Description
This is a convenience function to write the "source code" of inline Rexpressions. For example, if you want to write ‘`r 1+1`’ literally in anR Markdown document, you may write ‘`` `r knitr::inline_expr('1+1')```’; for Rnw documents, this may be‘\verb|\Sexpr{knitr::inline_expr{'1+1'}}|’.
Usage
inline_expr(code, syntax)Arguments
code | Character string of the inline R source code. |
syntax | A character string to specify the syntax, e.g. |
Value
A character string marked up using the inline R code syntax.
Examples
library(knitr)inline_expr("1+1", "rnw")inline_expr("1+1", "html")inline_expr("1+1", "md")Check the current input and output type
Description
The functionis_latex_output() returnsTRUE when the outputformat is LaTeX; it works for both ‘.Rnw’ and R Markdown documents (forthe latter, the two Pandoc formatslatex andbeamer areconsidered LaTeX output). The functionis_html_output() only works forR Markdown documents and will test for several Pandoc HTML based outputformats (by default, these formats are considered as HTML formats:c('markdown', 'epub', 'epub2', 'html', 'html4', 'html5', 'revealjs', 's5','slideous', 'slidy', 'gfm')).
Usage
is_latex_output()is_html_output(fmt = pandoc_to(), excludes = NULL)pandoc_to(fmt, exact = FALSE)pandoc_from(exact = FALSE)Arguments
fmt | A character vector of output formats to be checked against. If notprovided, |
excludes | A character vector of output formats that should not beconsidered as HTML format. Options are: markdown, epub, epub2, html, html4, html5,revealjs, s5, slideous, slidy, and gfm. |
exact | Whether to return or use the exact format name. If not, Pandocextensions will be removed from the format name, e.g., ‘latex-smart’will be treated as ‘latex’. |
Details
The functionpandoc_to() returns the Pandoc output format, andpandoc_from() returns Pandoc input format.pandoc_to(fmt)allows to check the current output format against a set of format names. Bothare to be used with R Markdown documents.
These functions may be useful for conditional output that depends on theoutput format. For example, you may write out a LaTeX table in an R Markdowndocument when the output format is LaTeX, and an HTML or Markdown table whenthe output format is HTML. Usepandoc_to(fmt) to test a more specificPandoc format.
Internally, the Pandoc output format of the current R Markdown document isstored inknitr::opts_knit$get('rmarkdown.pandoc.to'), and thePandoc input format inknitr::opts_knit$get('rmarkdown.pandoc.from')
Note
See available Pandoc formats, inPandoc's Manual
Examples
# check for output formats typeknitr::is_latex_output()knitr::is_html_output()knitr::is_html_output(excludes = c("markdown", "epub"))# Get current formatsknitr::pandoc_from()knitr::pandoc_to()# Test if current output format is 'docx'knitr::pandoc_to("docx")Compare two recorded plots
Description
Check if one plot only contains a low-level update of another plot.
Usage
is_low_change(p1, p2)Arguments
p1,p2 | Plot objects. |
Value
Logical value indicating whetherp2 is a low-level update ofp1.
Examples
pdf(NULL)dev.control("enable") # enable plot recordingplot(1:10)p1 = recordPlot()abline(0, 1) # add a line (a low-level change)p2 = recordPlot()plot(rnorm(100))p3 = recordPlot() # draw a completely new plotdev.off()knitr::is_low_change(p1, p2) # trueknitr::is_low_change(p1, p3) # falseCreate tables in LaTeX, HTML, Markdown and reStructuredText
Description
A very simple table generator, and it is simple by design. It is not intendedto replace any other R packages for making tables. Thekable()function returns a single table for a single data object, and returns a tablethat contains multiple tables if the input object is a list of data objects.Thekables() function is similar tokable(x) whenx is alist of data objects, butkables() accepts a list ofkable()values directly instead of data objects (see examples below).
Usage
kable( x, format, digits = getOption("digits"), row.names = NA, col.names = NA, align, caption = opts_current$get("tab.cap"), label = NULL, format.args = list(), escape = TRUE, ...)kables(x, format, caption = NULL, label = NULL)Arguments
x | For |
format | A character string. Possible values are |
digits | Maximum number of digits for numeric columns, passed to |
row.names | Logical: whether to include row names. By default, row namesare included if |
col.names | A character vector of column names to be used in the table. |
align | Column alignment: a character vector consisting of |
caption | The table caption. By default, it is retrieved from the chunkoption |
label | The table reference label. By default, the label is obtainedfrom |
format.args | A list of arguments to be passed to |
escape | Boolean; whether to escape special characters when producingHTML or LaTeX tables. When |
... | Other arguments (see Examples and References). |
Details
Missing values (NA) in the table are displayed asNA bydefault. If you want to display them with other characters, you can set theoptionknitr.kable.NA, e.g.options(knitr.kable.NA = '') tohideNA values.
You can set the optionknitr.kable.max_rows to limit the number ofrows to show in the table, e.g.,options(knitr.kable.max_rows = 30).
Value
A character vector of the table source code.
Note
When usingkable() as atop-level expression, you do notneed to explicitlyprint() it due to R's automatic implicitprinting. When it is wrapped inside other expressions (such as afor loop), you must explicitlyprint(kable(...)).
References
Seehttps://bookdown.org/yihui/rmarkdown-cookbook/kable.html for someexamples about this function, including specific arguments according to theformat selected.
See Also
Other R packages such ashuxtable,xtable,kableExtra,gt andtables for HTML and LaTeX tables, andascii andpander for different flavors of markdown output andsome advanced features and table styles. For more on other packages forcreating tables, seehttps://bookdown.org/yihui/rmarkdown-cookbook/table-other.html.
Examples
d1 = head(iris)d2 = head(mtcars)# pipe tables by defaultkable(d1)kable(d2[, 1:5])# no inner paddingkable(d2, format = "pipe", padding = 0)# more paddingkable(d2, format = "pipe", padding = 2)kable(d1, format = "latex")kable(d1, format = "html")kable(d1, format = "latex", caption = "Title of the table")kable(d1, format = "html", caption = "Title of the table")# use the booktabs packagekable(mtcars, format = "latex", booktabs = TRUE)# use the longtable packagekable(matrix(1000, ncol = 5), format = "latex", digits = 2, longtable = TRUE)# change LaTeX default table environmentkable(d1, format = "latex", caption = "My table", table.envir = "table*")# add some table attributeskable(d1, format = "html", table.attr = "id=\"mytable\"")# reST outputkable(d2, format = "rst")# no row nameskable(d2, format = "rst", row.names = FALSE)# Pandoc simple tableskable(d2, format = "simple", caption = "Title of the table")# format numbers using , as decimal point, and ' as thousands separatorx = as.data.frame(matrix(rnorm(60, 1e+06, 10000), 10))kable(x, format.args = list(decimal.mark = ",", big.mark = "'"))# save the valuex = kable(d2, format = "html")cat(x, sep = "\n")# can also set options(knitr.table.format = 'html') so that the output is HTML# multiple tables via either kable(list(x1, x2)) or kables(list(kable(x1),# kable(x2)))kable(list(d1, d2), caption = "A tale of two tables")kables(list(kable(d1, align = "l"), kable(d2)), caption = "A tale of two tables")Knit a document
Description
This function takes an input file, extracts the R code in it according to alist of patterns, evaluates the code and writes the output in another file.It can also tangle R source code from the input document (purl() is awrapper toknit(..., tangle = TRUE)). Theknitr.purl.inlineoption can be used to also tangle the code of inline expressions (disabled bydefault).
Usage
knit( input, output = NULL, tangle = FALSE, text = NULL, quiet = FALSE, envir = parent.frame(), encoding = "UTF-8")purl(..., documentation = 1L)Arguments
input | Path to the input file. |
output | Path to the output file for |
tangle | Boolean; whether to tangle the R code from the input file (like |
text | A character vector. This is an alternative way to provide theinput file. |
quiet | Boolean; suppress the progress bar and messages? |
envir | Environment in which code chunks are to be evaluated, forexample, |
encoding | Encoding of the input file; always assumed to be UTF-8 (i.e.,this argument is effectively ignored). |
... | arguments passed to |
documentation | An integer specifying the level of documentation to add tothe tangled script. |
Details
For most of the time, it is not necessary to set any options outside theinput document; in other words, a single call likeknit('my_input.Rnw') is usually enough. This function will try todetermine many internal settings automatically. For the sake ofreproducibility, it is better practice to include the options inside theinput document (to be self-contained), instead of setting them beforeknitting the document.
First the filename of the output document is determined in this way:‘foo.Rnw’ generates ‘foo.tex’, and other filename extensions like‘.Rtex’, ‘.Rhtml’ (‘.Rhtm’) and ‘.Rmd’(‘.Rmarkdown’) will generate ‘.tex’, ‘.html’ and ‘.md’respectively. For other types of files, if the filename contains‘_knit_’, this part will be removed in the output file, e.g.,‘foo_knit_.html’ creates the output ‘foo.html’; if ‘_knit_’ isnot found in the filename, ‘foo.ext’ will produce ‘foo.txt’ ifext is nottxt, otherwise the output is ‘foo-out.txt’. Iftangle = TRUE, ‘foo.ext’ generates an R script ‘foo.R’.
We need a set of syntax to identify special markups for R code chunks and Roptions, etc. The syntax is defined in a pattern list. All built-in patternlists can be found inall_patterns (call itapat). Firstknitr will try to decide the pattern list based on the filenameextension of the input document, e.g. ‘Rnw’ files use the listapat$rnw, ‘tex’ uses the listapat$tex, ‘brew’ usesapat$brew and HTML files useapat$html; for unkown extensions,the content of the input document is matched against all pattern lists toautomatically determine which pattern list is being used. You can alsomanually set the pattern list using theknit_patterns object orthepat_rnw series functions in advance andknitr willrespect the setting.
According to the output format (opts_knit$get('out.format')), a set ofoutput hooks will be set to mark up results from R (seerender_latex). The output format can be LaTeX, Sweave and HTML,etc. The output hooks decide how to mark up the results (you can customizethe hooks).
The nameknit comes from its counterpart ‘weave’ (as in Sweave),and the namepurl (as ‘tangle’ in Stangle) comes from a knittingmethod ‘knit one, purl one’.
If the input document has child documents, they will also be compiledrecursively. Seeknit_child.
See the package website and manuals in the references to know more aboutknitr, including the full documentation of chunk options and demos,etc.
Value
The compiled document is written into the output file, and the pathof the output file is returned. If thetext argument is notNULL, the compiled output is returned as a character vector. Inother words, if you provide a file input, you get an output filename; ifyou provide a character vector input, you get a character vector output.
Note
The working directory when evaluating R code chunks is the directory ofthe input document by default, so if the R code involves external files(likeread.table()), it is better to put these files under the samedirectory of the input document so that we can use relative paths. However,it is possible to change this directory with the package optionopts_knit$set(root.dir = ...) so all paths in code chunks arerelative to thisroot.dir. It is not recommended to change theworking directory viasetwd() in a code chunk, because it maylead to terrible consequences (e.g. figure and cache files may be writtento wrong places). If you do usesetwd(), please note thatknitr will always restore the working directory to the original one.Whenever you feel confused, printgetwd() in a code chunk to seewhat the working directory really is.
If theoutput argument is a file path, it is strongly recommended tobe in the current working directory (e.g. ‘foo.tex’ instead of‘somewhere/foo.tex’), especially when the output has externaldependencies such as figure files. If you want to write the output to adifferent directory, it is recommended to set the working directory to thatdirectory before you knit a document. For example, if the source documentis ‘foo.Rmd’ and the expected output is ‘out/foo.md’, you canwritesetwd('out/'); knit('../foo.Rmd') instead ofknit('foo.Rmd', 'out/foo.md').
N.B. There is no guarantee that the R script generated bypurl() canreproduce the computation done inknit(). Theknit() processcan be fairly complicated (special values for chunk options, custom chunkhooks, computing engines besides R, and theenvir argument, etc). Ifyou want to reproduce the computation in a report generated byknit(), be sure to useknit(), instead of merely executingthe R script generated bypurl(). This seems to be obvious, but somepeopledo notget it.
References
Package homepage:https://yihui.org/knitr/. Theknitrmain manual: andgraphics manual.
Seecitation('knitr') for the citation information.
Examples
library(knitr)(f = system.file("examples", "knitr-minimal.Rnw", package = "knitr"))knit(f) # compile to texpurl(f) # tangle R codepurl(f, documentation = 0) # extract R code onlypurl(f, documentation = 2) # also include documentationunlink(c("knitr-minimal.tex", "knitr-minimal.R", "figure"), recursive = TRUE)Convert markdown to HTML using knit() and mark_html()
Description
This is a convenience function to knit the input markdown source and callmarkdown::mark_html() in themarkdownpackage to convert the result to HTML.
Usage
knit2html( input, output = NULL, ..., envir = parent.frame(), text = NULL, quiet = FALSE, encoding = "UTF-8", force_v1 = getOption("knitr.knit2html.force_v1", FALSE))Arguments
input | Path to the input file. |
output | Path to the output file for |
... | Options passed to |
envir | Environment in which code chunks are to be evaluated, forexample, |
text | A character vector. This is an alternative way to provide theinput file. |
quiet | Boolean; suppress the progress bar and messages? |
encoding | Encoding of the input file; always assumed to be UTF-8 (i.e.,this argument is effectively ignored). |
force_v1 | Boolean; whether to force rendering the input document as anR Markdown v1 document, even if it is for v2. |
Value
If the argumenttext is NULL, a character string (HTML code)is returned; otherwise the result is written into a file and the filenameis returned.
Note
Themarkdown package is for R Markdown v1, which is much lesspowerful than R Markdown v2, i.e. thermarkdown package(https://rmarkdown.rstudio.com). To render R Markdown v2 documents toHTML, please usermarkdown::render() instead.
See Also
Examples
# a minimal examplewriteLines(c("# hello markdown", "```{r hello-random, echo=TRUE}", "rnorm(5)", "```"), "test.Rmd")knit2html("test.Rmd")if (interactive()) browseURL("test.html")unlink(c("test.Rmd", "test.html", "test.md"))Convert various input files to various output files usingknit() andPandoc
Description
Knits the input file and compiles to an output format using Pandoc.
Usage
knit2pandoc( input, output = NULL, tangle = FALSE, text = NULL, quiet = FALSE, envir = parent.frame(), to = "html", pandoc_wrapper = NULL, ..., encoding = "UTF-8")Arguments
input | Path to the input file. |
output | Path to the output file for |
tangle | Boolean; whether to tangle the R code from the input file (like |
text | A character vector. This is an alternative way to provide theinput file. |
quiet | Boolean; suppress the progress bar and messages? |
envir | Environment in which code chunks are to be evaluated, forexample, |
to | Character string giving the Pandoc output format to use. |
pandoc_wrapper | An R function used to call Pandoc. If |
... | Options to be passed to the |
encoding | Ignored (always assumes UTF-8). |
Value
Returns the output of thepandoc_wrapper function.
Author(s)
Trevor L. Davis
Convert Rnw or Rrst files to PDF
Description
Knit the input Rnw or Rrst document, and compile to PDF usingtinytex::latexmk() orrst2pdf().
Usage
knit2pdf( input, output = NULL, compiler = NULL, envir = parent.frame(), quiet = FALSE, ...)Arguments
input | Path to the input file. |
output | Path to the output file for |
compiler | A character string giving the LaTeX engine used to compilethe tex document to PDF. For an Rrst file, setting |
envir | Environment in which code chunks are to be evaluated, forexample, |
quiet | Boolean; suppress the progress bar and messages? |
... |
Value
The filename of the PDF file.
Note
Theoutput argument specifies the output filename to be passedto the PDF compiler (e.g. a tex document) instead of the PDF filename.
Author(s)
Ramnath Vaidyanathan, Alex Zvoleff and Yihui Xie
Examples
#' compile with xelatex## knit2pdf(..., compiler = 'xelatex')#' compile a reST file with rst2pdf## knit2pdf(..., compiler = 'rst2pdf')Knit an R Markdown document and post it to WordPress
Description
This function is a wrapper around theRWordPress package. It compilesan R Markdown document to HTML and post the results to WordPress. Please notethatRWordPress has not been updated for several years, which isnot a good sign. Forblogging with R, you may want to try theblogdown package instead.
Usage
knit2wp( input, title = "A post from knitr", ..., envir = parent.frame(), shortcode = FALSE, action = c("newPost", "editPost", "newPage"), postid, publish = TRUE)Arguments
input | Filename of the Rmd document. |
title | Title of the post. |
... | Other meta information of the post, e.g. |
envir | Environment in which code chunks are to be evaluated, forexample, |
shortcode | A length-2 logical vector: whether to use the shortcode‘[sourcecode lang='lang']’, which can be useful to WordPress.com usersfor syntax highlighting of source code and output. The first elementapplies to source code, and the second applies to text output. By default,both are |
action | Whether to create a new post, update an existing post, orcreate a new page. |
postid | If |
publish | Boolean: publish the post immediately? |
Note
This function will convert the encoding of the post and the title toUTF-8 internally. If you have additional data to send to WordPress (e.g.keywords and categories), you may have to manually convert them to theUTF-8 encoding with theiconv(x, to = 'UTF-8') function(especially when using Windows).
Author(s)
William K. Morris, Yihui Xie, and Jared Lander
References
https://yihui.org/knitr/demo/wordpress/
Examples
# see the referenceKnit a child document
Description
This function knits a child document and returns a character string to inputthe result into the main document. It is designed to be used in the chunkoptionchild and serves as the alternative to theSweaveInput command in Sweave.
Usage
knit_child(..., options = NULL, envir = knit_global())Arguments
... | Arguments passed to |
options | A list of chunk options to be used as global options insidethe child document. When one uses the |
envir | Environment in which code chunks are to be evaluated, forexample, |
Value
A character string of the content of the compiled child document isreturned as a character string so it can be written back to the parentdocument directly.
Note
This function is not supposed be called directly likeknit(); instead it must be placed in a parent document to letknit() call it indirectly.
The path of the child document is determined relative to the parent document.
References
https://yihui.org/knitr/demo/child/
Examples
# you can write \Sexpr{knit_child('child-doc.Rnw')} in an Rnw file 'main.Rnw'# to input results from child-doc.Rnw in main.tex# comment out the child doc by \Sexpr{knit_child('child-doc.Rnw', eval =# FALSE)}The code manager to manage code in all chunks
Description
This object provides methods to manage code (as character vectors) in allchunks inknitr source documents. For example,knitr::knit_code$get() returns a named list of all code chunks (thenames are chunk labels), andknitr::knit_code$get('foo') returns thecharacter vector of the code in the chunk with the labelfoo.
Usage
knit_codeFormat
An object of classlist of length 7.
Note
The methods on this object include theset() method (i.e., youcould do something likeknitr::knit_code$set(foo = "'my precious new code'")), but we recommend that you do not use this method to modify thecontent of code chunks, unless you areas creative as EmiTanaka and know what you are doing.
Engines of other languages
Description
This object controls how to execute the code from languages other than R(when the chunk optionengine is not'R'). Each component inthis object is a function that takes a list of current chunk options(including the source code) and returns a character string to be written intothe output.
Usage
knit_enginesFormat
An object of classlist of length 7.
Details
The engine function has one argumentoptions: the source code of thecurrent chunk is inoptions$code. Usually we can call externalprograms to run the code viasystem2. Other chunk options arealso contained in this argument, e.g.options$echo andoptions$eval, etc.
In most cases,options$engine can be directly used in command line toexecute the code, e.g.python orruby, but sometimes we maywant to specify the path of the engine program, in which case we can pass itthrough theengine.path option. For example,engine='ruby',engine.path='/usr/bin/ruby1.9.1'. Additional command line arguments can bepassed throughoptions$engine.opts, e.g.engine='ruby',engine.opts='-v'.
Seestr(knitr::knit_engines$get()) for a list of built-in languageengines.
Note
The Leiningen enginelein requires lein-exec plugin; seehttps://github.com/yihui/knitr/issues/1176 for details.
References
Usage:https://yihui.org/knitr/objects/; examples:https://yihui.org/knitr/demo/engines/
Examples
knit_engines$get("python")knit_engines$get("awk")names(knit_engines$get())Exit knitting early
Description
Sometimes we may want to exit the knitting process early, and completelyignore the rest of the document. This function provides a mechanism toterminateknit().
Usage
knit_exit(append, fully = TRUE)Arguments
append | A character vector to be appended to the results from |
fully | Whether to fully exit the knitting process if |
Value
InvisibleNULL. An internal signal is set up (as a sideeffect) to notifyknit() to quit as if it had reached the end of thedocument.
Examples
# see https://github.com/yihui/knitr-examples/blob/master/096-knit-exit.RmdA simple macro preprocessor for templating purposes
Description
This function expands a template based on the R expressions in{{}}(this tag can be customized by thedelim argument). These expressionsare extracted, evaluated and replaced by their values in the originaltemplate.
Usage
knit_expand(file, ..., text = read_utf8(file), delim = c("{{", "}}"))Arguments
file | The template file. |
... | A list of variables to be used for the code in the template; note thatthe variables will be searched for in the parent frame as well. |
text | Character vector of lines of code. An alternative way to specifythe template code directly. If |
delim | A pair of opening and closing delimiters for the templating tags. |
Value
A character vector, with the tags evaluated and replaced by theirvalues.
References
This function was inspired by the pyexpander and m4(http://www.gnu.org/software/m4/), thanks to Frank Harrell.
Examples
# see the knit_expand vignetteif (interactive()) browseVignettes(package = "knitr")Spell check filter for source documents
Description
When performing spell checking on source documents, we may need to skip Rcode chunks and inline R expressions, because many R functions and symbolsare likely to be identified as typos. This function is designed for thefilter argument ofaspell() to filter out code chunksand inline expressions.
Usage
knit_filter(ifile, encoding = "UTF-8")Arguments
ifile | Filename of the source document. |
encoding | Ignored (the file |
Value
A character vector of the file content, excluding code chunks andinline expressions.
Examples
library(knitr)knitr_example = function(...) system.file("examples", ..., package = "knitr")if (Sys.which("aspell") != "") { # -t means the TeX mode utils::aspell(knitr_example("knitr-minimal.Rnw"), knit_filter, control = "-t") # -H is the HTML mode utils::aspell(knitr_example("knitr-minimal.Rmd"), knit_filter, control = "-H -t")}The global environment for evaluating code
Description
Get or set the environment in which code chunks are evaluated.
Usage
knit_global(envir = NULL)Arguments
envir | If |
Hooks for R code chunks, inline R code and output
Description
A hook is a function of a pre-defined form (arguments) that takes values ofarguments and returns desired output. The objectknit_hooks is used toaccess or set hooks in this package.
Usage
knit_hooksFormat
An object of classlist of length 7.
References
Usage:https://yihui.org/knitr/objects/
Components inknit_hooks:https://yihui.org/knitr/hooks/
Examples
knit_hooks$get("source")knit_hooks$get("inline")Metadata about objects to be printed
Description
As an object is printed,knitr will collect metadata about it (ifavailable). After knitting is done, all the metadata is accessible via thisfunction. You can manually add metadata to theknitr session viaknit_meta_add().
Usage
knit_meta(class = NULL, clean = TRUE)knit_meta_add(meta, label = "")Arguments
class | Optionally return only metadata entries that inherit from thespecified class. The default, |
clean | Whether to clean the collected metadata. By default, themetadata stored inknitr is cleaned up once retrieved, because we maynot want the metadata to be passed to the next |
meta | A metadata object to be added to the session. |
label | A chunk label to indicate which chunk the metadata belongs to. |
Value
knit_meta() returns the matched metadata specified byclass;knit_meta_add() returns all current metadata.
Extract knit parameters from a document
Description
This function reads the YAML front-matter section of a document and returns alist of any parameters declared there. This function exists primarily tosupport the parameterized reports feature of thermarkdown package,however is also used by the knitrpurl function to includethe default parameter values in the R code it emits.
Usage
knit_params(text, evaluate = TRUE)Arguments
text | Character vector containing the document text. |
evaluate | Boolean. If |
Details
Parameters are included in YAML front matter using theparams key.This key can have any number of subkeys each of which represents aparameter. For example:
---title: My Documentoutput: html_documentparams: frequency: 10 show_details: true---
Parameter values can be provided inline as illustrated above or can beincluded in avalue sub-key. For example:
---title: My Documentoutput: html_documentparams: frequency: value: 10---
This second form is useful when you need to provide additional detailsabout the parameter (e.g. alabel field as describe above).
You can also use R code to yield the value of a parameter by prefacing the valuewith!r, for example:
---title: My Documentoutput: html_documentparams: start: !r Sys.Date()---
Value
List of objects of classknit_param that correspond to theparameters declared in theparams section of the YAML front matter.These objects have the following fields:
nameThe parameter name.
valueThe default value for the parameter.
exprThe R expression (if any) that yielded the default value.
In addition, other fields included in the YAML may also be presentalongside the name, type, and value fields (e.g. alabel fieldthat provides front-ends with a human readable name for the parameter).
Extract knit parameters from YAML text
Description
This function reads the YAML front-matter that has already been extractedfrom a document and returns a list of any parameters declared there.
Usage
knit_params_yaml(yaml, evaluate = TRUE)Arguments
yaml | Character vector containing the YAML text. |
evaluate | If |
Value
List of objects of classknit_param that correspond to theparameters declared in theparams section of the YAML. Seeknit_params for a full description of these objects.
See Also
Patterns to match and extract R code in a document
Description
Patterns are regular expressions and will be used in functions likebase::grep() to extract R code and chunk options. The objectknit_patterns controls the patterns currently used; see the referencesand examples for usage. All built-in patterns are available in the listall_patterns.
Usage
knit_patternsFormat
An object of classlist of length 7.
References
Usage:https://yihui.org/knitr/objects/
Components inknit_patterns:https://yihui.org/knitr/patterns/
See Also
Examples
library(knitr)opat = knit_patterns$get() # old pattern list (to restore later)apats = all_patterns # a list of all built-in patternsstr(apats)knit_patterns$set(apats[["rnw"]]) # set pattern list from apatsknit_patterns$get(c("chunk.begin", "chunk.end", "inline.code"))# a customized pattern list; has to empty the original patterns first!knit_patterns$restore()# we may want to use this in an HTML documentknit_patterns$set(list(chunk.begin = "<!--helloR\\s+(.*)", chunk.end = "^byeR-->"))str(knit_patterns$get())knit_patterns$set(opat) # put the old patterns backA custom printing function
Description
The S3 generic functionknit_print is the default printing function inknitr. The chunk optionrender uses this function by default.The main purpose of this S3 generic function is to customize printing of Robjects in code chunks. We can fall back to the normal printing behavior bysetting the chunk optionrender = normal_print.
Usage
knit_print(x, ...)normal_print(x, ...)Arguments
x | An R object to be printed |
... | Additional arguments passed to the S3 method. Currently ignored,except two optional arguments |
Details
Users can write custom methods based on this generic function. For example,if we want to print all data frames as tables in the output, we can define amethodknit_print.data.frame that turns a data.frame into a table (theimplementation may use other R packages or functions, e.g.xtable orkable()).
Value
The value returned from the print method should be a character vectoror can be converted to a character value. You can wrap the value inasis_output() so thatknitr writes the character valueas is in the output.
Note
It is recommended to leave a... argument in your method, toallow future changes of theknit_print() API without breaking yourmethod.
References
Seevignette('knit_print', package = 'knitr').
Examples
library(knitr)# write tables for data framesknit_print.data.frame = function(x, ...) { res = paste(c("", "", kable(x, output = FALSE)), collapse = "\n") asis_output(res)}# register the methodregisterS3method("knit_print", "data.frame", knit_print.data.frame)# after you define and register the above method, data frames will be printed# as tables in knitr, which is different with the default print() behaviorKnit package documentation
Description
Run examples in a package and insert output into the examples code;knit_rd_all() is a wrapper aroundknit_rd() to build staticHTML help pages for all packages under the ‘html’ directory of them.
Usage
knit_rd(pkg, links = tools::findHTMLlinks(), frame = TRUE)knit_rd_all()Arguments
pkg | Package name. |
links | A character vector of links to be passed to |
frame | Boolean: whether to put a navigation frame on the left of theindex page. |
Value
All HTML pages corresponding to topics in the package are writtenunder the current working directory. An ‘index.html’ is also writtenas a table of content.
Note
Ideally the html pages should be put under the ‘html’ directory ofan installed package which can be found viasystem.file('html', package = 'your_package_name'), otherwise some links may not work (e.g.the link to the DESCRITION file).
Examples
library(knitr)## Not run: knit_rd("maps")knit_rd("rpart")setwd(system.file("html", package = "ggplot2"))knit_rd("ggplot2") # time-consuming!knit_rd_all() # this may take really long time if you have many packages installed## End(Not run)Syntax highlighting themes
Description
This object can be used to set or get themes inknitr for syntaxhighlighting.
Usage
knit_themeFormat
An object of classlist of length 2.
Details
We can useknit_theme$set(theme) to set the theme, andknit_theme$get(theme) to get a theme. Thetheme is a characterstring for both methods (either the name of the theme, or the path to the CSSfile of a theme), and for theset() method, it can also be a listreturned by theget() method. See examples below.
Note
The syntax highlighting here only applies to ‘.Rnw’ (LaTeX) and‘.Rhtml’ (HTML) documents, and it does not work for other types ofdocuments, such as ‘.Rmd’ (R Markdown, which has its own syntaxhighlighting themes; seehttps://rmarkdown.rstudio.com).
Author(s)
Ramnath Vaidyanathan and Yihui Xie
References
For a preview of all themes, seehttps://gist.github.com/yihui/3422133.
Examples
opts_knit$set(out.format = "latex")knit_theme$set("edit-vim")knit_theme$get() # names of all available themesthm = knit_theme$get("acid") # parse the theme to a listknit_theme$set(thm)opts_knit$set(out.format = NULL) # restore optionWatch an input file continuously and knit it when it is updated
Description
Check the modification time of an input file continously in an infinite loop.Whenever the time indicates the file has been modified, call a function torecompile the input file.
Usage
knit_watch(input, compile = knit, interval = 1, ...)Arguments
input | An input file path, or a character vector of mutiple input file paths. |
compile | A function to compile the |
interval | A time interval to pause in each cycle of the infinite loop. |
... | Other arguments to be passed to the |
Details
This is actually a general function not necessarily restricted toapplications inknitr. You may specify anycompile function toprocess theinput file. To stop the infinite loop, press the‘Escape’ key or ‘Ctrl + C’ (depending on your editing environmentand operating system).
Examples
# knit_watch('foo.Rnw', knit2pdf)# knit_watch('foo.Rmd', rmarkdown::render)Load the cache database of a code chunk
Description
If a code chunk has turned on the chunk optioncache = TRUE, a cachedatabase will be established after the document is compiled. You can use thisfunction to manually load the database anywhere in the document (even beforethe code chunk). This makes it possible to use objects created later in thedocument earlier, e.g. in an inline R expression before the cached codechunk, which is normally not possible becauseknitr compiles thedocument in a linear fashion, and objects created later cannot be used beforethey are created.
Usage
load_cache( label, object, notfound = "NOT AVAILABLE", path = opts_chunk$get("cache.path"), dir = opts_knit$get("output.dir"), envir = NULL, lazy = TRUE)Arguments
label | The chunk label of the code chunk that has a cache database. |
object | The name of the object to be fetched from the database. If itis missing, |
notfound | A value to use when the |
path | Path of the cache database (normally set in the global chunkoption |
dir | Path to use as the working directory. Defaults to the outputdirectory if run inside aknitr context and to the current workingdirectory otherwise. Any relative |
envir | Environment to use for cache loading, into which all objects inthe cache for the specified chunk (not just that in |
lazy | Whether to |
Value
InvisibleNULL whenobject is not specified (the cachedatabase will be loaded as a side effect), otherwise the value of theobject if found.
Note
Apparently this function loads the value of the object from theprevious run of the document, which may be problematic when thevalue of the object becomes different the next time the document iscompiled. Normally you must compile the document twice to make sure thecache database is created, and the object can be read from it. Please usethis function with caution.
References
See the example #114 athttps://github.com/yihui/knitr-examples.
Default and current chunk options
Description
Options for R code chunks. When running R code, the objectopts_chunk(default options) is not modified by chunk headers (local chunk options aremerged with default options), whereasopts_current (current options)changes with different chunk headers and it always reflects the options forthe current chunk.
Usage
opts_chunkopts_currentFormat
An object of classlist of length 7.
An object of classlist of length 7.
Details
Normally we set up the global options once in the first code chunk in adocument usingopts_chunk$set(), so that alllatter chunks willuse these options. Note the global options set in one chunk will not affectthe options in this chunk itself, and that is why we often need to set globaloptions in a separate chunk.
Seestr(knitr::opts_chunk$get()) for a list of default chunk options.
Note
opts_current should be treated as read-only and you are supposedto only query its values viaopts_current$get(). Callingopts_current$set() will throw an error.
References
Usage:https://yihui.org/knitr/objects/
A list of available options:https://yihui.org/knitr/options/#chunk-options
Examples
opts_chunk$get("prompt")opts_chunk$get("fig.keep")Hooks for code chunk options
Description
Likeknit_hooks, this object can be used to set hook functionsto manipulate chunk options.
Usage
opts_hooksFormat
An object of classlist of length 7.
Details
For every code chunk, if the chunk option named, say,FOO, is notNULL, and a hook function with the same name has been set viaopts_hooks$set(FOO = function(options) { options }) (you can manipuatetheoptions argument in the function and return it), the hook functionwill be called to update the chunk options.
References
https://yihui.org/knitr/hooks/
Examples
# make sure the figure width is no smaller than fig.heightopts_hooks$set(fig.width = function(options) { if (options$fig.width < options$fig.height) { options$fig.width = options$fig.height } options})# remove all hooksopts_hooks$restore()Options for the knitr package
Description
Options including whether to use a progress bar when knitting a document, andthe base directory of images, etc.
Usage
opts_knitFormat
An object of classlist of length 7.
Details
Besides the standard usage (opts_knit$set()), we can also set packageoptions prior to loadingknitr or callingknit() usingoptions() in base R. A global optionknitr.package.fooinoptions() will be set as an optionfoo inopts_knit,i.e. global options in base R with the prefixknitr.package.correspond to options inopts_knit. This can be useful to set packageoptions in ‘~/.Rprofile’ without loadingknitr.
Seestr(knitr::opts_knit$get()) for a list of default package options.
References
Usage:https://yihui.org/knitr/objects/
A list of available options:https://yihui.org/knitr/options/#package-options
Examples
opts_knit$get("verbose")opts_knit$set(verbose = TRUE) # change itif (interactive()) { # for unnamed chunks, use 'fig' as the figure prefix opts_knit$set(unnamed.chunk.label = "fig") knit("001-minimal.Rmd") # from https://github.com/yihui/knitr-examples}Template for creating reusable chunk options
Description
Creates a template binding a label to a set of chunk options. Every chunkthat references the template label will have the specified set of optionsapplied to it.
Usage
opts_templateFormat
An object of classlist of length 7.
Examples
opts_template$set(myfigures = list(fig.height = 4, fig.width = 4))# later you can reuse these chunk options by 'opts.label', e.g.# <<foo, opts.label='myfigures'>>=# the above is equivalent to <<foo, fig.height=4, fig.width=4>>=A Pandoc wrapper to convert documents to other formats
Description
This function calls Pandoc to convert documents to other formats such asHTML, LaTeX/PDF and Word, etc, (optionally) based on a configuration file orin-file configurations which specify the options to use for Pandoc.
Usage
pandoc(input, format, config = getOption("config.pandoc"), ext = NA)Arguments
input | A character vector of Markdown filenames (must be encoded inUTF-8). |
format | Name of the output format (see References). This can be acharacter vector of multiple formats; by default, it is obtained from the |
config | Path to the Pandoc configuration file. If missing, it isassumed to be a file with the same base name as the |
ext | Filename extensions. By default, the extension is inferred fromthe |
Details
There are two ways to input the Pandoc configurations – through a configfile, or embed the configurations in the input file as special commentsbetween<!--pandoc and-->.
The configuration file is a DCF file (seeread.dcf). This filemust contain a field namedt which means the output format. Theconfigurations are written in the form oftag:value and passed toPandoc (if no value is needed, just leave it empty, e.g. the optionstandalone ors for short). If there are multiple outputformats, write each format and relevant configurations in a block, andseparate blocks with blank lines.
If there are multiple records of thet field in the configuration, theinput markdown file will be converted to all these formats by default, unlesstheformat argument is specified as one single format.
Value
The output filename(s) (or an error if the conversion failed).
References
Pandoc:https://pandoc.org; Examples and rules of theconfigurations:https://yihui.org/knitr/demo/pandoc/
Also see R Markdown (v2) athttps://rmarkdown.rstudio.com. Thermarkdown package has several convenience functions and templatesthat make it very easy to use Pandoc. The RStudio IDE also hascomprehensive support for it, so I'd recommend users who are not familiarwith command-line tools to use thermarkdown package instead.
See Also
Examples
system("pandoc -h") # see possible output formatsPartition chunk options from the code chunk body
Description
This is a wrapper function callingxfun::divide_chunk()under the hood.
Usage
partition_chunk(engine, code)Set regular expressions to read input documents
Description
These are convenience functions to set pre-defined pattern lists (the syntaxto read input documents). The function names are built from correspondingfile extensions, e.g.pat_rnw() can set the Sweave syntax to read Rnwdocuments.
Usage
pat_rnw()pat_brew()pat_tex()pat_html()pat_md()pat_rst()pat_asciidoc()pat_textile()Value
The patterns objectknit_patterns is modified as a sideeffect.
Examples
# see how knit_patterns is modifiedknit_patterns$get()pat_rnw()knit_patterns$get()knit_patterns$restore() # empty the listCrop a plot (remove the edges) using PDFCrop or ImageMagick
Description
The programpdfcrop (often shipped with a LaTeX distribution) isexecuted on a PDF plot file, andmagick::image_trim() is executed for othertypes of plot files.
Usage
plot_crop(x, quiet = TRUE)Arguments
x | Filename of the plot. |
quiet | Whether to suppress standard output from the command. |
Details
The programpdfcrop can crop the extra white margins when the plotformat is PDF, to make better use of the space in the output document,otherwise we often have to struggle withgraphics::par() to setappropriate margins. Notepdfcrop often comes with a LaTeXdistribution such as TinyTeX, MiKTeX, or TeX Live, and you may not need toinstall it separately (useSys.which('pdfcrop') to check it; if it notempty, you are able to use it). Note thatpdfcrop depends onGhostScript. You can check if GhostScript is installed viatools::find_gs_cmd().
Value
The original filename.
References
PDFCrop:https://www.ctan.org/pkg/pdfcrop. If you useTinyTeX, you may installpdfcrop withtinytex::tlmgr_install('pdfcrop').
An unevaluated expression to return .Random.seed if exists
Description
This expression returns.Random.seed wheneval(rand_seed) andNULL otherwise.
Usage
rand_seedDetails
It is designed to work withopts_chunk$set(cache.extra = rand_seed)for reproducibility of chunks that involve with random number generation. Seereferences.
References
https://yihui.org/knitr/demo/cache/
Examples
eval(rand_seed)rnorm(1) # .Random.seed is created (or modified)eval(rand_seed)Mark character strings as raw blocks in R Markdown
Description
Wraps content in a raw attribute block, which protects it from being escapedby Pandoc. Seehttps://pandoc.org/MANUAL.html#generic-raw-attribute.Functionsraw_latex() andraw_html() are shorthands ofraw_block(x, 'latex') andraw_block(x, 'html'), respectively.
Usage
raw_block(x, type = "latex", ...)raw_latex(x, ...)raw_html(x, ...)Arguments
x | The character vector to be protected. |
type | The type of raw blocks (i.e., the Pandoc output format). If youare not sure about the Pandoc output format of your document, insert a codechunk |
... | Arguments to be passed to |
Examples
knitr::raw_latex("\\emph{some text}")Read chunks from an external script
Description
Chunks can be put in an external script, and this function reads chunks intothe currentknitr session;read_demo() is a convenience functionto read a demo script from a package.
Usage
read_chunk( path, lines = read_utf8(path), labels = NULL, from = NULL, to = NULL, from.offset = 0L, to.offset = 0L, roxygen_comments = TRUE)read_demo(topic, package = NULL, ...)Arguments
path | Path to the R script. |
lines | Character vector of lines of code. By default, this is read from |
labels | Character vector of chunk labels (default |
from,to | Numeric vector specifying the starting/ending line numbers ofcode chunks, or a character vector; see Details. |
from.offset,to.offset | Offsets to be added to |
roxygen_comments | Logical dictating whether to keep trailingroxygen-style comments from code chunks in addition to whitespace |
topic,package | Name of the demo and the package. See |
... | Arguments passed to |
Details
There are two approaches to read external code into the current session: (1)Use a special separator of the from## ---- chunk-label (at least fourdashes before the chunk label) in the script; (2) Manually specify thelabels, starting and ending positions of code chunks in the script.
The second approach will be used only whenlabels is notNULL.For this approach, iffrom isNULL, the starting position is 1;ifto isNULL, each of its element takes the next element offrom minus 1, and the last element ofto will be the length oflines (e.g. whenfrom = c(1, 3, 8) and the script has 10 linesin total,to will bec(2, 7, 10)). Alternatively,fromandto can be character vectors as regular expressions to specify thepositions; when their length is 1, the single regular expression will bematched against thelines vector, otherwise each element offrom/to is matched againstlines and the match issupposed to be unique so that the numeric positions returned fromgrep() will be of the same length offrom/to. Notelabels always has to match the length offrom andto.
Value
As a side effect, code chunks are read into the current session sothat future chunks can (re)use the code by chunk label references. If anexternal chunk has the same label as a chunk in the current session, chunklabel references by future chunks will refer to the external chunk.
Note
This function can only be used in a chunk which isnot cached(chunk optioncache = FALSE), and the code is read and stored in thecurrent sessionwithout being executed (to actually run the code,you have to use a chunk with a corresponding label).
Author(s)
Yihui Xie; the idea of the second approach came from PeterRuckdeschel (author of theSweaveListingUtils package)
References
https://yihui.org/knitr/demo/externalization/
Examples
## put this in foo.R and read_chunk('foo.R')## ---- my-label ----1 + 1lm(y ~ x, data = data.frame(x = 1:10, y = rnorm(10)))## later you can use <<my-label>>= to reference this chunk## the 2nd approachcode = c("#@a", "1+1", "#@b", "#@a", "rnorm(10)", "#@b")read_chunk(lines = code, labels = "foo") # put all code into one chunk named fooread_chunk(lines = code, labels = "foo", from = 2, to = 2) # line 2 into chunk fooread_chunk(lines = code, labels = c("foo", "bar"), from = c(1, 4), to = c(3, 6))# automatically figure out 'to'read_chunk(lines = code, labels = c("foo", "bar"), from = c(1, 4))read_chunk(lines = code, labels = c("foo", "bar"), from = "^#@a", to = "^#@b")read_chunk(lines = code, labels = c("foo", "bar"), from = "^#@a", to = "^#@b", from.offset = 1, to.offset = -1)## later you can use, e.g., <<foo>>=knitr::knit_code$get() # use this to check chunks in the current sessionknitr::knit_code$restore() # clean up the sessionSet or get output hooks for different output formats
Description
Therender_*() functions set built-in output hooks for LaTeX, HTML,Markdown, reStructuredText, AsciiDoc, and Textile. Thehooks_*()functions return a list of the output hooks for the corresponding format.
Usage
render_html()hooks_html()render_asciidoc()hooks_asciidoc()render_latex()hooks_latex()render_sweave()hooks_sweave(envirs = c("Sinput", "Soutput", "Schunk"))render_listings()hooks_listings(envirs = c("Sinput", "Soutput", "Schunk"))render_markdown(strict = FALSE, fence_char = "`")hooks_markdown(strict = FALSE, fence_char = "`")render_jekyll(highlight = c("pygments", "prettify", "none"), extra = "")hooks_jekyll(highlight = c("pygments", "prettify", "none"), extra = "")render_rst(strict = FALSE)hooks_rst(strict = FALSE)render_textile()hooks_textile()Arguments
envirs | Names of LaTeX environments for code input, output, and chunk. |
strict | Boolean; whether to use strict markdown or reST syntax. For markdown, if |
fence_char | A single character to be used in the code blocks fence.This can be e.g. a backtick or a tilde, depending on your Markdown renderingengine. |
highlight | Which code highlighting engine to use: if |
extra | Extra tags for the highlighting engine. For |
Details
There are three variants of Markdown documents: ordinary Markdown(render_markdown(strict = TRUE), which callshooks_markdown(strict = TRUE)), extended Markdown (e.g., GitHubFlavored Markdown and Pandoc;render_markdown(strict = FALSE), whichcallshooks_markdown(strict = FALSE)), and Jekyll (a blogging systemon GitHub;render_jekyll(), which callshooks_jekyll()).
For LaTeX output, there are three variants:knitr's default style(render_latex(), which callshooks_latex() and uses the LaTeXframed package), Sweave style (render_sweave(), which callshooks_sweave() and uses ‘Sweave.sty’), and listings style(render_listings(), which callshooks_listings() and uses LaTeXlistings package).
Default HTML output hooks are set byrender_html() (which callshooks_html());render_rst() (which callshooks_rst()) isfor reStructuredText;render_textile() (which callshooks_textile()) is for Textile, andrender_asciidoc() (whichcallshooks_asciidoc()) is AsciiDoc.
Therender_*() functions can be used beforeknit() or in thefirst chunk of the input document (ideally this chunk has optionsinclude = FALSE andcache = FALSE) so that all the followingchunks will be formatted as expected.
You can also useknit_hooks to set the format's hooks with thehooks_*() functions; see references for more info on furthercustomizing output hooks.
Value
NULL forrender_* functions; corresponding hooks areset as a side effect. A list of output hooks forhooks_*()functions.
References
See output hooks inhttps://yihui.org/knitr/hooks/, andsome examples inhttps://bookdown.org/yihui/rmarkdown-cookbook/output-hooks.html
Jekyll and Liquid:https://github.com/jekyll/jekyll/wiki/Liquid-Extensions; prettify.js:https://code.google.com/archive/p/google-code-prettify
Examples
# below is pretty much what knitr::render_markdown() does:knitr::knit_hooks$set(knitr::hooks_markdown())# you can retrieve a subset of the hooks and set them, e.g.,knitr::knit_hooks$set(knitr::hooks_markdown()["source"])knitr::knit_hooks$restore()Convert an ‘Rnw’ document to PDF
Description
Callknit() to compile the ‘.Rnw’ input to ‘.tex’,and thentinytex::latexmk() to convert ‘.tex’ to‘.pdf’.
Usage
rnw2pdf( input, output = with_ext(input, "pdf"), compiler = "xelatex", envir = parent.frame(), quiet = FALSE, clean = TRUE, error = FALSE, ...)Arguments
input | Path to the input file. |
output | Path of the PDF output file. By default, it uses the same nameas the |
compiler,... | The LaTeX engine and other arguments to be passed to |
envir | Environment in which code chunks are to be evaluated, forexample, |
quiet | Boolean; suppress the progress bar and messages? |
clean | If |
error | If |
Details
This function is similar toknit2pdf(), with the following differences:
The default compiler is "xelatex" instead of "pdflatex".
outputuses the file extension ".pdf" instead of ".tex".Before knitting, it tries to remove the
outputfile and will throw a clear error if the file cannot be removed.outputcould be under any dir, not necessarily the same directory asinput.It cleans up intermediate files by default, including the ".tex" file.
It stops knitting when any error occurs (by setting the chunk option
error = FALSE).
Value
Theoutput file path.
Knit R Markdown using the classic Docco style
Description
The classic Docco style is a two-column layout, with text in the left andcode in the right column.
Usage
rocco(input, ...)Arguments
input | Path of the input R Markdown file. |
... | Arguments to be passed to |
Details
The output HTML page supports resizing and hiding/showing the two columns.Move the cursor to the center of the page, and it will change to abidirectional resize cursor; drag the cursor to resize the two columns. Pressthe keyt to hide the code column (show the text column only), andpress again to hide the text column (show code).
Value
An HTML file is written, and its name is returned.
Author(s)
Weicheng Zhu and Yihui Xie
References
The Docco package by Jeremy Ashkenas:https://github.com/jashkenas/docco
Examples
rocco_view = function(input) { owd = setwd(tempdir()) on.exit(setwd(owd)) if (!file.exists(input)) return() o = rocco(input, quiet = TRUE) if (interactive()) browseURL(o)}# knit these two vignettes using the docco stylerocco_view(system.file("doc", "docco-classic.Rmd", package = "knitr"))rocco_view(system.file("doc", "knit_expand.Rmd", package = "knitr"))A wrapper for rst2pdf
Description
Convert reST to PDF usingrst2pdf (which converts from rst to PDFusing the ReportLab open-source library).
Usage
rst2pdf(input, command = "rst2pdf", options = "")Arguments
input | The input rst file. |
command | Character string giving the path of the |
options | Extra command line options, e.g. |
Value
An input file ‘*.rst’ will produce ‘*.pdf’ and this outputfilename is returned if the conversion was successful.
Author(s)
Alex Zvoleff and Yihui Xie
References
https://github.com/rst2pdf/rst2pdf
See Also
Set aliases for chunk options
Description
We do not have to use the chunk option names given inknitr; we can setaliases for them. The aliases are a named character vector; the names arealiases and the elements in this vector are the real option names.
Usage
set_alias(...)Arguments
... | Named arguments. Argument names are aliases, and argument valuesare real option names. |
Value
NULL.opts_knit$get('aliases') is modified as the side effect.
Examples
set_alias(w = "fig.width", h = "fig.height")# then we can use options w and h in chunk headers instead of fig.width and# fig.heightSet the header information
Description
Some output documents may need appropriate header information. For example,for LaTeX output, we need to write ‘\usepackage{tikz}’ into thepreamble if we use tikz graphics; this function sets the header informationto be written into the output.
Usage
set_header(...)Arguments
... | Header components; currently possible components are |
Details
By default,knitr will set up the header automatically. For example, ifthe tikz device is used,knitr will add ‘\usepackage{tikz}’ tothe LaTeX preamble, and this is done by setting the header componenttikz to be a character string:set_header(tikz ='\usepackage{tikz}'). Similary, when we highlight R code using thehighlight package (i.e. the chunk optionhighlight = TRUE),knitr will set thehighlight component of the header vectorautomatically; if the output type is HTML, this component will be different– instead of LaTeX commands, it contains CSS definitions.
For power users, all the components can be modified to adapt to a customizedtype of output. For instance, we can changehighlight to LaTeXdefinitions of thelistings package (and modify the output hooksaccordingly), so we can decorate R code using thelistings package.
Value
The header vector inopts_knit is set.
Examples
set_header(tikz = "\\usepackage{tikz}")opts_knit$get("header")Specify the parent document of child documents
Description
This function extracts the LaTeX preamble of the parent document to use forthe child document, so that the child document can be compiled as anindividual document.
Usage
set_parent(parent)Arguments
parent | Path to the parent document, relative to the current childdocument. |
Details
When the preamble of the parent document also contains code chunks and inlineR code, they will be evaluated as if they were in this child document. Forexamples, whenknitr hooks or other options are set in the preamble ofthe parent document, it will apply to the child document as well.
Value
The preamble is extracted and stored to be used later when thecomplete output is written.
Note
Obviously this function is only useful when the output format is LaTeX.This function only works when the child document is compiled in astandalone mode usingknit() (instead of being called inknit_child()); when the parent document is compiled, thisfunction in the child document will be ignored.
References
https://yihui.org/knitr/demo/child/
Examples
## can use, e.g. \Sexpr{set_parent('parent_doc.Rnw')} or# <<setup-child, include=FALSE>>=# set_parent('parent_doc.Rnw')# @Wrap evaluated results for output
Description
This function is mainly for internal use: it is called on each part of theoutput of the code chunk (code, messages, text output, and plots, etc.) afterall statements in the code chunk have been evaluated, and will sew thesepieces of output together into a character vector.
Usage
sew(x, options = list(), ...)Arguments
x | Output from |
options | A list of chunk options used to control output. |
... | Other arguments to pass to methods. |
Spin goat's hair into wool
Description
This function takes a specially formatted R script and converts it to aliterate programming document. By default normal text (documentation) shouldbe written after the roxygen comment (#') and code chunk options arewritten after#| or#+ or# %% or# ----.
Usage
spin( hair, knit = TRUE, report = TRUE, text = NULL, envir = parent.frame(), format = c("Rmd", "Rnw", "Rhtml", "Rtex", "Rrst", "qmd"), doc = "^#+'[ ]?", inline = "^[{][{](.+)[}][}][ ]*$", comment = c("^[# ]*/[*]", "^.*[*]/ *$"), precious = !knit && is.null(text))Arguments
hair | Path to the R script. The script must be encoded in UTF-8 if itcontains multibyte characters. |
knit | Logical; whether to compile the document after conversion. |
report | Logical; whether to generate a report for ‘Rmd’,‘Rnw’ and ‘Rtex’ output. Ignored if |
text | A character vector of code, as an alternative way to provide theR source. If |
envir | Environment for |
format | Character; the output format. The default is R Markdown. |
doc | A regular expression to identify the documentation lines; bydefault it follows the roxygen convention, but it can be customized, e.g.if you want to use |
inline | A regular expression to identify inline R expressions; bydefault, code of the form |
comment | A pair of regular expressions for the start and end delimitersof comments; the lines between a start and an end delimiter will beignored. By default, the delimiters are |
precious | logical: whether intermediate files (e.g., |
Details
Obviously the goat's hair is the original R script, and the wool is theliterate programming document (ready to be knitted).
Value
Iftext isNULL, the path of the final output document,otherwise the content of the output.
Note
If the output format isRnw and no document class is specifiedin roxygen comments, this function will automatically add thearticle class to the LaTeX document so that it is complete and canbe compiled. You can always specify the document class and other LaTeXsettings in roxygen comments manually.
When the output format isRmd, it is compiled to HTML viaknit2html(), which uses R Markdown v1 instead of v2. If youwant to use the latter, you should callrmarkdown::render() instead. Similarly, if theoutput format isqmd, you need to render the output with Quarto.
Author(s)
Yihui Xie, with the original idea from Richard FitzJohn (who named itassowsear() which meant to make a silk purse out of a sow's ear)
References
https://yihui.org/knitr/demo/stitch/
See Also
stitch (feed a template with an R script)
Spin a child R script
Description
This function is similar toknit_child() but is used in Rscripts instead. When the main R script is not called viaspin(), this function simply executes the child script viasys.source(), otherwise it callsspin() to spinthe child script into a source document, and usesknit_child()to compile it. You can call this function in R code, or using the syntax ofinline R expressions inspin() (e.g.{{knitr::spin_child('script.R')}}).
Usage
spin_child(input, format)Arguments
input | Filename of the input R script. |
format | Passed to |
Value
A character string of the knitted R script.
Automatically create a report based on an R script and a template
Description
This is a convenience function for small-scale automatic reporting based onan R script and a template. The default template is an Rnw file (LaTeX);stitch_rhtml() andstitch_rmd() are wrappers on top ofstitch() using the R HTML and R Markdown templates respectively.
Usage
stitch( script, template = system.file("misc", "knitr-template.Rnw", package = "knitr"), output = NULL, text = NULL, envir = parent.frame())stitch_rhtml(..., envir = parent.frame())stitch_rmd(..., envir = parent.frame())Arguments
script | Path to the R script. |
template | Path of the template to use. By default, the Rnw template inthis package; there is also an HTML template inknitr. |
output | Output filename, passed to |
text | A character vector. This is an alternative way to provide theinput file. |
envir | Environment in which code chunks are to be evaluated, forexample, |
... | Arguments passed to |
Details
The first two lines of the R script can contain the title and author of thereport in comments of the form ‘## title:’ and ‘## author:’. Thetemplate must have a token ‘%sCHUNK_LABEL_HERE’, which will be used toinput all the R code from the script. See the examples below.
The R script may contain chunk headers of the form ‘## ---- label,opt1=val1, opt2=val2’, which will be copied to the template; if no chunkheaders are found, the whole R script will be inserted into the template asone code chunk.
Value
path of the output document
See Also
spin (turn a specially formatted R script to a report)
Examples
s = system.file("misc", "stitch-test.R", package = "knitr")if (interactive()) stitch(s) # compile to PDF# HTML reportstitch(s, system.file("misc", "knitr-template.Rhtml", package = "knitr"))# or convert markdown to HTMLstitch(s, system.file("misc", "knitr-template.Rmd", package = "knitr"))unlink(c("stitch-test.html", "stitch-test.md", "figure"), recursive = TRUE)Package vignette engines
Description
Since R 3.0.0, package vignettes can use non-Sweave engines, andknitrhas provided a few engines to compile vignettes viaknit() withdifferent templates. Seehttps://yihui.org/knitr/demo/vignette/ formore information.
Note
If you use theknitr::rmarkdown engine, please make sure thatyou putrmarkdown in the ‘Suggests’ field of your‘DESCRIPTION’ file. Also make surepandoc is availableduringR CMD build. If you build your package from RStudio, thisis normally not a problem. If you build the package outside RStudio, runrmarkdown::find_pandoc() in an R session to check if Pandoc can befound.
When thermarkdown package is not installed or not available, orpandoc cannot be found, theknitr::rmarkdown engine willfall back to theknitr::knitr engine, which uses R Markdown v1 basedon themarkdown package.
Examples
library(knitr)vig_list = tools::vignetteEngine(package = "knitr")str(vig_list)vig_list[["knitr::knitr"]][c("weave", "tangle")]vig_list[["knitr::knitr_notangle"]][c("weave", "tangle")]vig_list[["knitr::docco_classic"]][c("weave", "tangle")]Wrap long lines in Rmd files
Description
This function wraps long paragraphs in an R Markdown file. Other elements arenot wrapped: the YAML preamble, fenced code blocks, section headers andindented elements. The main reason for wrapping long lines is to make iteasier to review differences in version control.
Usage
wrap_rmd(file, width = 80, text = NULL, backup)Arguments
file | The input Rmd file. |
width | The expected line width. |
text | A character vector of text lines, as an alternative to |
backup | Path to back up the original file in case anything goeswrong. If set to |
Value
Iffile is provided, it is overwritten; iftext isprovided, a character vector is returned.
Note
Currently it does not wrap blockquotes or lists (ordered or unordered).This feature may or may not be added in the future.
Examples
wrap_rmd(text = c("```", "1+1", "```", "- a list item", "> a quote", "", paste(rep("this is a normal paragraph", 5), collapse = " ")))Generate BibTeX bibliography databases for R packages
Description
A wrapper function ofxfun::pkg_bib().
Usage
write_bib(..., prefix = getOption("knitr.bib.prefix", "R-"))Arguments
...,prefix | Arguments passed to |