3.2 Chunk Options
If you want to set chunk options globally, call knitr::opts_chunk$set()
in a code chunk (usually the first one in the document), e.g.,
```{r, label="setup", include=FALSE}
knitr::opts_chunk$set(
comment = "#>",
echo = FALSE,
fig.width = 6
)
```
Chunk options are written in the form tag=value
. A special chunk option is the chunk label (e.g., setup
in the above example). Only the chunk label does not need a tag (i.e., you can only provide the value). If you prefer the form tag=value
, you could also use the chunk option label explicitly, e.g., label="setup"
.
The settings will apply to every chunk in your file as a default. You can overwrite them in individual chunk headers.
Full list of chunk options: https://yihui.org/knitr/options/
Chunk options can customize nearly all components of code chunks, such as the source code, text output, plots, and the language of the chunk.
Other languages are supported in Rmd
You can list the names of all available engines via:
names(knitr::knit_engines$get())
## [1] "awk" "bash" "coffee"
## [4] "gawk" "groovy" "haskell"
## [7] "lein" "mysql" "node"
## [10] "octave" "perl" "php"
## [13] "psql" "Rscript" "ruby"
## [16] "sas" "scala" "sed"
## [19] "sh" "stata" "zsh"
## [22] "asis" "asy" "block"
## [25] "block2" "bslib" "c"
## [28] "cat" "cc" "comment"
## [31] "css" "ditaa" "dot"
## [34] "embed" "eviews" "exec"
## [37] "fortran" "fortran95" "go"
## [40] "highlight" "js" "julia"
## [43] "python" "R" "Rcpp"
## [46] "sass" "scss" "sql"
## [49] "stan" "targets" "tikz"
## [52] "verbatim" "theorem" "lemma"
## [55] "corollary" "proposition" "conjecture"
## [58] "definition" "example" "exercise"
## [61] "hypothesis" "proof" "remark"
## [64] "solution" "marginfigure"
The engines from theorem
to solution
are only available when you use the bookdown package, and the rest are shipped with the knitr package.
To use a different language engine, you can change the language name in the chunk header from r
to the engine name, e.g.,
For engines that rely on external interpreters such as python
, perl
, and ruby
, the default interpreters are obtained from Sys.which()
, i.e., using the interpreter found via the environment variable PATH
of the system. If you want to use an alternative interpreter, you may specify its path in the chunk option engine.path
.
For example, you may want to use Python 3 instead of the default Python 2, and we assume Python 3 is at /usr/bin/python3
- All outputs support markdown syntax.
- If the output is html, you can write in html syntax.
The chunk label for each chunk is assumed to be unique within the document. This is especially important for cache and plot filenames, because these filenames are based on chunk labels. Chunks without labels will be assigned labels like unnamed-chunk-i
, where i
is an incremental number.
Chunk label doesn’t need a
tag
, i.e., you only provide thevalue
.If you prefer the form
tag=value
, you could also use the chunk optionlabel
explicitly, e.g.,
You may use knitr::opts_chunk$set()
to change the default values of chunk options in a document.
Commonly used chunk options
- Complete list here. Or
?opts_chunk
to get the help page.
Options | Definitions |
---|---|
echo=TRUE |
Whether to display the source code in the output document. Use this when you want to show the output but NOT the source code itself. |
eval=TRUE |
Whether to evaluate the code chunk. |
include=TRUE |
Whether to include the chunk code and output in the output document—including source code, text output, messages, warnings, and plots. If FALSE , nothing will be written into the output document, but the code is still evaluated and plot files are generated if there are any plots in the chunk, so you can manually insert figures later. |
message=TRUE |
Whether to preserve messages emitted by message() |
warning=TRUE |
Whether to show warnings in the output produced by warning() . |
results='markup' |
Controls how to display the text results. When results='markup' that is to write text output as-is, i.e., write the raw text results directly into the output document without any markups.Useful when priting stargazer tables. |
comment='##' |
The prefix to be added before each line of the text output. Set comment = '' remove the default ## . |
collapse=FALSE |
Whether to, if possible, collapse all the source and output blocks from one code chunk into a single block (by default, they are written to separate blocks). This option only applies to Markdown documents. |
fig.keep='high' |
How plots in chunks should be kept. high : Only keep high-level plots (merge low-level changes into high-level plots). none : Discard all plots. all : Keep all plots (low-level plot changes may produce new plots). first : Only keep the first plot. last : Only keep the last plot. If set to a numeric vector, the values are indices of (low-level) plots to keep. If you want to choose the second to the fourth plots, you could use fig.keep = 2:4 (or remove the first plot via fig.keep = -1 ). |
fig.align="center" |
Figure alignment. |
fig.pos="H" |
A character string for the figure position arrangement to be used in \begin{figure}[] . |
fig.cap |
Figure caption. |
results='markup'
note plural form for results.
results='markup'
: Default. Mark up text output with the appropriate environments depending on the output format. For example, for R Markdown, if the text output is a character string"[1] 1 2 3"
, the actual output that knitr produces will be:In this case,
results='markup'
means to put the text output in fenced code blocks (```).results='asus'
: Write text output as-is, i.e., write the raw text results directly into the output document without any markups.Sometime, you encounter the following error messages when you have R codes within
enumerate
environment.You can’t use
macro parameter character #
in horizontal mode.By default, knitr prefixes R output with
##
, which can’t be present in your TeX file.Solution:
- specify
results="asis"
in code chunks.
- specify
results='hold'
: Hold all pieces of text output in a chunk and flush them to the end of the chunk.results='hide'
(orresults='FALSE'
): Hide text output.
collapse = FALSE
Whether to merge text output and source code into a single code block in the output. The default FALSE
means R expressions and their text output are separated into different blocks.
collapse = TRUE
makes the output more compact, since the R source code and its text output are displayed in a single output block. The default collapse = FALSE
means R expressions and their text output are separated into different blocks.
Hooks
The object knit_hooks
in the knitr package is used to set hooks; the basic usage is knitr::knit_hooks$set(name = FUN)
(see objects for details) where name
is the name of a chunk option (can be arbitrary), and FUN
is a function.
There are two types of hooks:
chunk hooks and
A chunk hook is a function that is triggered by a chunk option when the value of this chunk option is not
NULL
.output hooks
Output hooks control over output from your code chunks, such as source code, text output, messages, and plots.
Hook functions may have different forms, depending what they are designed to do.
Chunk hooks
For example, we define a custom chunk hook function for the small_mar
option
knitr::knit_hooks$set(small_mar = function(before, ...) {
if (before)
par(mar = c(4, 4, .1, .1)) # smaller top/right margin
})
Then this function will be called for a chunk option like the following (small_mar
doesn’t have to be TRUE
; it can be any non-NULL
value):
Output hooks
With the knitr package, you have control over every piece of output from your code chunks, such as source code, text output, messages, and plots. The control is achieved through “output hooks.”
Available output hook names:
## [1] "source" "output" "warning" "message"
## [5] "error" "plot" "inline" "chunk"
## [9] "text" "evaluate.inline" "evaluate" "document"
Note that these names of output hooks are reserved by knitr, so you must NOT use these names for your custom chunk hooks.
source
: processing the source code.output
: processing text output.
You may obtain the actual hooks from the object knit_hooks
via the get()
method, e.g.,
# for meaningful output, the code below should be
# executed *inside* a code chunk of a knitr document
knitr::knit_hooks$get("source")
knitr::knit_hooks$get("output")
# or knitr::knit_hooks$get(c('source', 'output'))
A custom output hook is registered through the set()
method of knit_hooks
. Because this method will override the existing default hook, we recommend that you save a copy of an existing hook, process the output elements in your own way, and pass the results to the default hook.
When the text output from a code chunk is lengthy, you may want to only show the first few lines. For example, when printing a data frame of a few thousand rows, it may not be helpful to show the full data, and the first few lines may be enough. Below we redefine the output
hook so that we can control the maximum number of lines via a custom chunk option out.lines
:
# save the built-in output hook
hook_output <- knitr::knit_hooks$get("output")
# set a new output hook to truncate text output
knitr::knit_hooks$set(output = function(x, options) {
if (!is.null(n <- options$out.lines)) {
x <- xfun::split_lines(x)
if (length(x) > n) {
# truncate the output
x <- c(head(x, n), "....\n")
}
x <- paste(x, collapse = "\n")
}
hook_output(x, options)
})
The basic idea of the above hook function is that if the number of lines of the text output is greater than the threshold set in the chunk option out.lines
(stored in the variable n
in the function body), we only keep the first n
lines and add an ellipsis (....
) to indicate the output is truncated.
Now we can test the new output
hook by setting the chunk option out.lines = 4
on the chunk below:
## speed dist
## 1 4 2
## 2 4 10
## 3 7 4
....
And you see four lines of output as expected.
## speed dist
## 1 4 2
## 2 4 10
## 3 7 4
## 4 7 22
## 5 8 16
## 6 9 10
## 7 10 18
## 8 10 26
## 9 10 34
## 10 11 17
Since we have stored the original output
hook in hook_output
, we can restore it by calling the set()
method again:
Now we print the data frame again. The default behavior is to print the whole data frame.
## speed dist
## 1 4 2
## 2 4 10
## 3 7 4
## 4 7 22
## 5 8 16
## 6 9 10
## 7 10 18
## 8 10 26
## 9 10 34
## 10 11 17
References:
- Output hooks: https://bookdown.org/yihui/rmarkdown-cookbook/output-hooks.html
- Chunk hooks: https://bookdown.org/yihui/rmarkdown-cookbook/chunk-hooks.html