@[toc]( <center> knitr 01)
title: "Untitled"
author: "ks_c"
date: "2021/1/30"
output: html_document
近日正研究r markdown,见作者有一knitr包的解释,本想翻阅一二,奈何英语令人头大得紧,故作罢。
由于缺乏阅读经验,英文文章总是看完下句忘上句。本想直接机翻,可终究也是信不过蛮夷机器的。于是只好借助谷歌翻译,躬身译yihui xie,Options:Chunk options and package options至中文,如此。
事先声明,鄙人英文是漏洞百出,预估本文也是挂一漏万。姑妄言之,若有大方之家光临"寒舍",万请不吝赐教。
侵删。
目录(可以点击各章节查看原文)
-
Chunk Options #代码块的设置
- Code evaluation #代码的运算
- Text output #文本输出
- Code decoration #代码装饰
- Cache #缓存
- Plots #图
- Animation #动画
- Code chunk #代码块
- Child documents #子文件(?)
- Language engines #语言引擎
- Option templates #选项模板
- Extracting source code #提取源码
- Other chunk options # 其他设置
- Package Options # 包的设置
The knitr package provides a lot of chunk options for customizing nearly all components of code chunks, such as the source code, text output, plots, and the language of the chunk.
It also offers some options at the package level to customize the knitting process.
This page documents all chunk options and package options available in knitr.
The default values of these options are in parentheses in the list items.
Knitr软件包提供了许多自定义选项块,几乎可以用于所有代码块的组件,例如源代码,文本输出,图表和块的语言。
它还在包装级别提供了一些选项以自定义输出过程。
此页面记录了knitr包中所有可用的模块选项和软件包选项。
这些选项的默认值在列表项的括号中。
Chunk Options
Chunk options are written in chunk headers.
The syntax for chunk headers depends on the document format, e.g., for .Rnw documents (R + LaTeX), chunk headers are written with << >>=, and for .Rmd documents, chunk headers are written with {r}. The examples below are primarily for .Rmd documents (R Markdown), but in most cases, the chunk options can be used with any document format. 块选项写在块头中。 块头的语法取决于文档格式。例如,对于.Rnw文档(R + LaTeX),块头用<< >> =编写,对于.Rmd文档,块头用
{r }。
以下示例主要用于.Rmd文档(R Markdown),但是在大多数情况下,块选项可以与任何文档格式一起使用。
Chunk options are written in the form tag=value like this:
模块选项以 tag = value 的形式编写,如下所示:
print("hello,world")
#my-chunk :该代码块的名称
#echo=F :没有回声,即不现实代码
#fig.height=4 :高度为4(英寸)
#dev='jpeg' :
A special chunk option is the chunk label (e.g., my-chunk in the above example). Only the chunk label does not need a tag (i.e., you only provide the value).
If you prefer the form tag=value, you could also use the chunk option label explicitly, e.g.,
代码块名称是一个特殊的块选项(例如,上例中的my-chunk)。仅块标签不需要标签(即,您仅提供值)。
如果您希望使用tag = value的形式,则还可以显式使用块选项标签,例如:
#label可以省略
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.
每个块的块名称在文档中都是唯一的。
这对于缓存和绘图文件名特别重要,因为这些文件名基于块名。
没有名的块将被分配标签,例如unnamed-chunk-i,其中i是一个递增数字。
You may use knitr::opts_chunk$set() to change the default values of chunk options in a document. For example, you may put this in the first code chunk of your document:
您可以使用knitr :: opts_chunk $ set()更改文档中块选项的默认值。 例如,您可以将其放在文档的第一个代码块中:
(新建一个rmd文件时都会有第一个代码块默认为该代码块。)
knitr::opts_chunk$set(
comment = '', fig.width = 6, fig.height = 6
)
Below are a few more tips about chunk options:
The chunk header must be written on one line. You must not break the line.
1.块头必须写在一行上。 不要分行。Try to avoid spaces, periods (.), and underscores () in chunk labels and paths. If you need separators, you are recommended to use hyphens (-) instead. For example, setup-options is a good label, whereas setup.options and chunk 1 are bad; fig.path = 'figures/mcmc-' is a good path for figure output, and fig.path = 'markov chain/monte carlo' is bad.
2.尽量避免在块标签和路径中出现空格,句点(。)和下划线()。 如果需要分隔符,建议改用连字符(-)。 例如,setup-options是一个很好的标签,而setup.options和块1是不好的标签; fig.path ='figures / mcmc-'是输出图形的好路径,而fig.path ='markov chain / monte carlo'是不好的。-
All option values must be valid R expressions. You may think of them as values to be passed to function arguments.
3.所有选项值必须是有效的R表达式。 您可能会将它们视为要传递给函数参数的值。For example, options that take character values must be quoted, e.g., results = 'asis' and out.width = '\textwidth' (remember that a literal backslash needs double backslashes).例如,必须使用带字符值的选项加引号,例如,结果='asis'和out.width ='\ textwidth'(请记住,文字反斜杠需要双反斜杠)
In theory, the chunk label should be quoted, too. However, for the sake of convenience, it will be automatically quoted if you did not (e.g., ```{r, 2a} will parsed as ```{r, '2a'}).从理论上讲,块标签也应加引号。 但是,为方便起见,如果您未将其自动引用(例如,```{r,2a}将被解析为`''{r,'2a'}.块名可以加""也可以不加。
You can write arbitrarily complicated expressions as long as they are valid R code.您可以编写任意复杂的表达式,只要它们是有效的R代码即可。
Below is a list of chunk options in knitr documented in the format “option: (default value; type of value)“.以下是knitr中存储的选项,这些选项在option:(default value; type of value)这种格式下。
Code evaluation
eval: (TRUE; logical or numeric) Whether to evaluate the code chunk.
It can also be a numeric vector to choose which R expression(s) to evaluate, e.g., eval = c(1, 3, 4) will evaluate the first, third, and fourth expressions, and eval = -(4:5) will evaluate all expressions except the fourth and fifth.
eval(默认为T,逻辑或数值型)是否呈现出该代码块。
也可以是数值型,eval =c(1,3,4)为第1,3,4行输出,eval =-(4:5)第4:5行不输出。
如果设置为{r "1", eval=c(1,2,5,6)},那么将运算1,2行和5,6行,没有被选中的行则在前边加两个##:
a <- 1
a
b <- 2
b
c <- 3
c
输出:
a <- 1
a
## [1] 1
## b <- 2
## b
c <- 3
c
## [1] 3
Text output
-
echo: (TRUE; logical or numeric) Whether to display the source code in the output document.
Besides TRUE/FALSE, which shows/hides the source code, we can also use a numeric vector to choose which R expression(s) to echo in a chunk, e.g., echo = 2:3 means to echo only the 2nd and 3rd expressions, and echo = -4 means to exclude the 4th expression.
echo(默认为T,逻辑或数值)是否在文档中呈现源代码。
除了T/F之外,也可以用数字向量来决定那几行会呈现。例如echo=2:3将呈现2到3行的内容(由于本文是直接在简书编辑器中编辑的,so没有办法完美模仿出rstudio的输出结果。)
#全部计算,但是文档中只输出1,2行源码。
a <- 1
a
b <- 2
b
c <- 3
c
输出:
a <- 1
a
## [1] 1
#这里本应有一个b<-2,由于echo而没有显示,但是结果却输出了。
## [1] 2
c <- 3
c
## [1] 3
和eval的区别:eval是决定源码是否运算,eval为evaluate的缩写。而echo为是否在输出文档中呈现这段代码(如果不设置eval就是全部运算,显示出echo设定的部分)。
-
results: ('markup'; character) Controls how to display the text results.
Note that this option only applies to normal text output (not warnings, messages, or errors). The possible values are as follows:
result(默认为markup,字符串):控制如何呈现结果。
注意:此选项仅适用于普通文本(不适用于警告,消息或错误)
result的值有四种,分别如下。-
markup: 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: [1] 1 2 3。 In this case, results='markup' means to put the text output in fenced code blocks (```).
markup:根据输出格式用适当的环境中标记文本输出。
如果文本输出是字符串“ [1] 1 2 3”,则knitr产生的实际输出将是:[1] 1 23。在这种情况下,results ='markup'的意思是 将文本输出放在单独的代码块中。
-
markup: Mark up text output with the appropriate environments depending on the output format.
a <- 1
a
b <- 2
b
输出:
a <- 1
a
## [1] 1
b
## [1] 2
-
asis: Write text output as-is, i.e., write the raw text results directly into the output document without any markups.
直接按原样输出文本,即,将原始文本结果直接写入输出文档中,而无需任何标记。
a <- 1
a
[1] 1b
[1] 2
- hold: Hold all pieces of text output in a chunk and flush them to the end of the chunk.
将所有文本输出保留在末尾的一个块中,
输出:
- hide (or FALSE): Hide text output.
隐藏输出结果。
-
collapse: (FALSE; logical) 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.
collapse:(F;逻辑)如果可能的话,是否将所有源码和输出从不同的代码块collapse(折叠)到一个块中(默认情况下,它们被写入单独的块中)。 此选项仅适用于Markdown文档。
输出:
print()函数块的collapse=F
warning: (TRUE; logical) Whether to preserve warnings (produced by warning()) in the output. If FALSE, all warnings will be printed in the console instead of the output document.
It can also take numeric values as indices to select a subset of warnings to include in the output. Note that these values reference the indices of the warnings themselves (e.g., 3 means “the third warning thrown from this chunk”) and not the indices of which expressions are allowed to emit warnings.error: (TRUE; logical) Whether to preserve errors (from stop()). By default, the code evaluation will not stop even in case of errors! If we want to stop on errors, we need to set this option to FALSE. Note that R Markdown has changed this default value to FALSE. When the chunk option include = FALSE, knitr will stop on error, because it is easy to overlook potential errors in this case.
message: (TRUE; logical) Whether to preserve messages emitted by message() (similar to the option warning).
warning、error、message为是否呈现这三种信息,不再赘述。
7.** include**: (TRUE; logical) Whether to include the chunk output in the output document. 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.
(默认为T;逻辑)是否在输出文档中包括块输出。 如果为FALSE,输出文档中将不会任何输出结果,但是代码仍会执行,图也会继续生成,因此您可以稍后手动插入图形。
输出:
strip.white: (TRUE; logical) Whether to remove blank lines in the beginning or end of a source code block in the output.
strip.white(默认为T):是否移除开头或结尾的空白行。(实测:html文档中F和T均不会移除空白行,可能是操纵有误。)class.output: (NULL; character) A vector of class names to be added to the text output blocks. This option only works for HTML output formats in R Markdown. For example, with class.output = c('foo', 'bar'), the text output will be placed in <pre class="foo bar"></pre>.
class.output:(NULL;字符)要添加到文本输出块的类名称的向量。 此选项仅适用于R Markdown中的HTML输出格式。 例如,使用class.output = c('foo','bar'),文本输出将放置在<pre class =“ foo bar”> </ pre>中。 即文本输出会在另一个块中。
class.message/class.warning/class.error: (NULL; character) Similar to class.output, but applied to messages, warnings, and errors in R Markdown output. Please see the “Code Decoration” section for class.source, which applies similarly to source code blocks.
class.message / class.warning / class.error:(NULL;字符)类似于class.output,但适用于R Markdown输出中的消息,警告和错误。 请参阅class.source的“代码修饰”部分,该部分类似地适用于源代码块。attr.output/attr.message/attr.warning/attr.error: (NULL; character) Similar to the class.* options above, but for specifying arbitrary fenced code block attributes for Pandoc; class.* is a special application of attr.*, e.g., class.source = 'numberLines' is equivalent to attr.source = '.numberLines', but attr.source can take arbitrary attribute values, e.g., attr.source = c('.numberLines', 'startFrom="11"').
attr.output / attr.message / attr.warning / attr.error :(空值;字符)类似于上面的class。···选项,但用于为Pandoc指定任意受保护的代码块属性; class。···是attr.···的特殊应用,例如,class.source ='numberLines'等效于attr.source ='.numberLines',但是attr.source可以采用任意属性值,例如attr.source = c ('.numberLines','startFrom =“ 11”')render: (knitr::knit_print; function(x, options, ...)) A function to print the visible values in a chunk. The value passed to the first argument of this function (i.e., x) is the value evaluated from each expression in the chunk. The list of current chunk options is passed to the argument options. This function is expected to return a character string. For more information, check out the package vignette about custom chunk rendering: vignette('knit_print', package = 'knitr').
render(渲染):(knitr :: knit_print; function(x,options,...))一个用于以块形式打印可见值的函数。 传递给此函数的第一个参数的值(即x)是从块中每个代码运算的值。 当前块选项列表将传递给参数选项。 该函数应返回一个字符串。 有关更多信息,请查看有关自定义块渲染的程序包简介:vignette('knit_print',package ='knitr')
如果上一个模块定义的函数dummy(x, ...),这个函数无论传入什么参数都只会告诉你‘nothing’,没有render到下一个模块,那么……
现在将render=dummy:
其他的解释可见:vignette('knit_print',package ='knitr')中的render。
-
split: (FALSE; logical) Whether to split the output into separate files and include them in LaTeX by \input{} or HTML by <iframe></iframe>. This option only works for .Rnw, .Rtex, and .Rhtml documents.
(默认为F;逻辑)是将输出拆分为单独的文件,然后通过\ input {}将其包含在LaTeX中(选T时),还是通过<iframe> </ iframe>将其包含在HTML中(选F时)。 此选项仅适用于.Rnw,.Rtex和.Rhtml文档 。
这个在html文档操作时也没发现有什么变化。
Code decoration
-
tidy: (FALSE) Whether to reformat the R code. Other possible values are as follows:将R代码重新排列整齐,默认为F。
- TRUE (equivalent to tidy = 'formatR'): Call the function formatR::tidy_source() to reformat the code. T等同于"formatR",使用formatR::tidy_source() 函数来整理。
- 'styler': Use styler::style_text() to reformat the code.
- A custom function of the form function(code, ...) {} to return the reformatted code.
- If reformatting fails, the original R code will not be changed (with a warning).
tidy.opts
: (NULL
; list) A list of options to be passed to the function determined by thetidy
option, e.g.,tidy.opts = list(blank = FALSE, width.cutoff = 60)
fortidy = 'formatR'
to remove blank lines and try to cut the code lines at 60 characters.
默认为NULL,决定tidy的选项。比如tidy.opts = list(blank = FALSE, width.cutoff = 60)
就是移除空白行并且将代码剪为60个字符。
-
prompt
: (FALSE
; logical) Whether to add the prompt characters in the R code. Seeprompt
andcontinue
on the help page?base::options
. Note that adding prompts can make it difficult for readers to copy R code from the output, soprompt = FALSE
may be a better choice. This option may not work well when the chunk optionengine
is notR
(#1274).
(默认为F; 逻辑)是否在R代码中添加提示字符。
请参阅帮助页面base :: options上的提示和继续。
请注意,添加提示可能会使读者难以从输出中复制R代码,因此``prompt=F''可能是一个更好的选择。
当块选项引擎不是R时,此选项可能无法正常工作。
效果:
prompt=T时在每段前边会有一个>符号。
- comment: ('##'; character) The prefix to be added before each line of the text output.
By default, the text output is commented out by ##, so if readers want to copy and run the source code from the output document, they can select and copy everything from the chunk, since the text output is masked in comments (and will be ignored when running the copied text). Set comment = ' ' remove the default ##.
在文本输出的每一行之前添加的前缀(两个井号)。
如果读者想复制并运行输出文档中的源代码,他们可以选择并复制块中的所有内容,因为文本输出被注释掩盖了(并且将 运行复制的文本时被忽略)。 设置注释=' '可以删除默认的##,文本输出前边没有注释。括号中也可以添加其他内容,输出文本前就会有设定好的内容
highlight: (TRUE; logical) Whether to syntax highlight the source code.高亮(默认为true),不同类型的元素会用不同的颜色高亮出来。上图中就是数字为蓝色,引号内为浅红色,‘function’为深红色
class.source: (NULL; character) Class names for source code blocks in the output document. Similar to the class.* options for output such as class.output.
attr.source: (NULL; character) Attributes for source code blocks. Similar to the attr.* options for output such as attr.output.
size
: ('normalsize'
; character) Font size of the chunk output from.Rnw
documents. See this page for possible sizes.background
: ('#F7F7F7'
; character) Background color of the chunk output of.Rnw
documents. 背景。(默认为#F7F7F7,天空灰)
FFFFFF为纯白
-
indent
: (character) A string to be added to each line of the chunk output.
Typically it consists of white spaces.
This option is assumed to be read-only, and knitr sets its value while parsing the document.
For example, for the chunk below,indent
is a character string of two spaces:
```{r}
rnorm(10)
```
indent(字符)要添加到块输出的每一行的字符串。 通常,它由空白组成。 通常此选项为只读,并且** knitr **在解析文档时设置其值。 例如,对于下面的块,'indent`是两个空格的字符串:
@[toc]( <center> knitr翻译02)
title: "Untitled"
author: "ks_c"
date: "2021/1/31"
output: html_document
本次翻译接下来三节:
Cache
1.cache
-
cache
: (FALSE
; logical) Whether to cache a code chunk.
When evaluating code chunks for the second time, the cached chunks are skipped (unless they have been modified), but the objects created in these chunks are loaded from previously saved databases (.rdb
and.rdx
files), and these files are saved when a chunk is evaluated for the first time, or when cached files are not found (e.g., you may have removed them by hand).
Note that the filename consists of the chunk label with an MD5 digest of the R code and chunk options of the code chunk, which means any changes in the chunk will produce a different MD5 digest, and hence invalidate the cache. See more information on this page.
(默认为FALSE;逻辑)是否缓存代码块。
当第二次运行代码块时,将跳过缓存的块(除非已对其进行修改),但是在这些块中创建的对象是从先前保存的数据库(.rdb和.rdx文件)中加载的,这些第一次运行块时或未找到缓存文件时(例如,您可能已手动删除它们),文件将被保存。
请注意,文件名由带有R代码的MD5摘要和代码块的块选项的块标签组成,这意味着该块中的任何更改都会产生不同的MD5摘要,从而使缓存无效。
2. cache.path
-
cache.path
: ('cache/'
; character) A prefix to be used to generate the paths of cache files. For R Markdown, the default value is based on the input filename, e.g., the cache paths for the chunk with the labelFOO
in the fileINPUT.Rmd
will be of the formINPUT_cache/FOO_*.*
.
('cache /'
; 字符串)用于生成缓存文件路径的前缀。 对于R Markdown,默认值基于输入文件名,例如,文件INPUT.Rmd中标签为FOO''的块的缓存路径将采用
INPUT_cache / FOO _ 。''的形式。
3. cache.vars
-
cache.vars
: (NULL
; character) A vector of variable names to be saved in the cache database. By default, all variables created in the current chunks are identified and saved, but you may want to manually specify the variables to be saved, because the automatic detection of variables may not be robust, or you may want to save only a subset of variables.
(默认NULL,字符)要保存在缓存数据库中的变量名的向量。 默认情况下,将识别并保存在当前块中创建的所有变量,但是您可能希望手动指定要保存的变量,因为自动检测变量可能不够可靠,或者您可能只想保存一部分变量
4. cache.globals
-
cache.globals
: (NULL
; character) A vector of the names of variables that are not created from the current chunk. This option is mainly forautodep = TRUE
to work more precisely—a chunkB
depends on chunkA
when any ofB
’s global variables areA
’s local variables. In case the automatic detection of global variables in a chunk fails, you may manually specify the names of global variables via this option (see #1403for an example).
(默认为NULL
;字符串)不是从当前块创建的变量名的向量。 此选项主要是为了使autodep = TRUE更精确地工作---当B模块的变量是A模块的变量时,B依靠A。 如果自动检测块中的全局变量失败,则可以通过此选项手动指定全局变量的名称
5. cache.lazy
-
cache.lazy
: (TRUE
; logical) Whether tolazyLoad()
or directlyload()
objects. For very large objects, lazyloading may not work, socache.lazy = FALSE
may be desirable (see #572).
延迟加载(默认为T)是要lazyLoad()还是直接是load()对象。 对于非常大的对象,延迟加载可能不起作用,因此可能需要``cache.lazy = FALSE''
6. cache.comments
-
cache.comments
: (NULL
; logical) IfFALSE
, changing comments in R code chunks will not invalidate the cache database.
(NULL;逻辑)如果为FALSE,则在R代码块中更改注释不会使高速缓存数据库无效
7. cache.rebuild
-
cache.rebuild
: (FALSE
; logical) IfTRUE
, reevaluate the chunk even if the cache does not need to be invalidated. This can be useful when you want to conditionally invalidate the cache, e.g.,cache.rebuild = !file.exists("some-file")
can rebuild the chunk whensome-file
does not exist (see #238).
(FALSE
;逻辑)如果为``TRUE'',则即使不需要使缓存无效也要重新运行源码块。 当您想有条件地使缓存无效时,这很有用,例如,cache.rebuild =!file.exists(“ some-file”)
可以在不存在some-file`的情况下重建块
8. dependson
dependson
: (NULL
; character or numeric) A character vector of chunk labels to specify which other chunks this chunk depends on. This option applies to cached chunks only—sometimes the objects in a cached chunk may depend on other cached chunks, so when other chunks are changed, this chunk must be updated accordingly.
dependson
:(NULL
;字符或数字)块标签的字符向量,用于指定该块所依赖的其他块。 此选项仅适用于高速缓存的块-有时,高速缓存的块中的对象可能取决于其他高速缓存的块,因此,在更改其他大块时,必须相应地更新该大块。If
dependson
is a numeric vector, it means the indices of chunk labels, e.g.,dependson = 1
means this chunk depends on the first chunk in the document, anddependson = c(-1, -2)
means it depends on the previous two chunks (negative indices stand for numbers of chunks before this chunk, and note they are always relative to the current chunk).如果Dependson是数字向量,则表示块标签的索引,例如Dependson = 1表示此块取决于文档中的第一个块,而Dependson = c(-1,-2)表示 它取决于前两个块(负索引代表该块之前的块数,请注意,它们始终相对于当前块)。Please note this option does not work when set as a global chunk option via
opts_chunk$set()
; it must be set as a local chunk option.请注意,通过opts_chunk $ set()设置为全局块选项时,此选项不起作用; 必须将其设置为本地块选项。autodep
: (FALSE
; logical) Whether to analyze dependencies among chunks automatically by detecting global variables in the code (may not be reliable), sodependson
does not need to be set explicitly.autodep:(FALSE;逻辑)是否通过检测代码中的全局变量来自动分析块之间的依赖关系(可能不可靠),所以不需要显式设置dependson。
Plots
fig.path
: ('figure/'
; character) A prefix to be used to generate figure file paths.fig.path
and chunk labels are concatenated to generate the full paths. It may contain a directory likefigure/prefix-
; the directory will be created if it does not exist.('figure /'; character)用于生成图形文件路径的前缀。 fig.path和块标签被串联以生成完整路径。 它可能包含一个目录,如图/前缀-; 如果目录不存在,将创建该目录。fig.keep
: ('high'
; character) How plots in chunks should be kept. Possible values are as follows:如何保存代码块中的图
* `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. 数值向量为保存第几张图
Low-level plotting commands include `lines()` and `points()`, etc. To better understand `fig.keep`, consider the following chunk:
```
```{r, test-plot}
plot(1) # high-level plot
abline(0, 1) # low-level change
plot(rnorm(10)) # high-level plot
# many low-level changes in a loop (a single R expression)
for(i in 1:10) {
abline(v = i, lty = 2)
}
```
```
Normally this produces 2 plots in the output (because `fig.keep = 'high'`). For `fig.keep = 'none'`, no plots will be saved. For `fig.keep = 'all'`, 4 plots are saved. For `fig.keep = 'first'`, the plot produced by `plot(1)` is saved. For `fig.keep = 'last'`, the last plot with 10 vertical lines is saved.
-
fig.show
: ('asis'
; character) How to show/arrange the plots. Possible values are as follows:如何显示/安排图。 可能的值如下:
该部分类似文字输出部分的设置。
* `asis`: Show plots exactly in places where they were generated (as if the code were run in an R terminal).该在哪在哪
* `hold`: Hold all plots and output them at the end of a code chunk.所有图都在最后
* `animate`: Concatenate all plots into an animation if there are multiple plots in a chunk.多个图变成动画连续播放
* `hide`: Generate plot files but hide them in the output document. 隐藏
-
dev
: ('pdf'
for LaTeX output and'png'
for HTML/Markdown; character) The graphical device to generate plot files. All graphics devices in base R and those in Cairo, cairoDevice, svglite, ragg, and tikzDevice are supported, e.g.,pdf
,png
,svg
,jpeg
,tiff
,cairo_pdf
,CairoJPEG
,CairoPNG
,Cairo_pdf
,Cairo_png
,svglite
,ragg_png
,tikz
, and so on. Seenames(knitr:::auto_exts)
for the full list. Besides these devices, you can also provide a character string that is the name of a function of the formfunction(filename, width, height)
. The units for the image size are always inches (even for bitmap devices, in which DPI is used to convert between pixels and inches).
输出格式。(对于LaTeX输出是pdf'',对于HTML / Markdown是
png''; 字符)用于生成绘图文件的图形设备。
支持Base R中的所有图形设备以及** Cairo , cairoDevice , svglite , ragg 和 tikzDevice *中的所有图形设备,例如pdf,png ,svg,jpeg,tiff,cairo_pdf,cairoJPEG,cairoPNG,cairo_pdf,cairo_png,svglite,ragg_png,tikz等。 有关完整列表,请参见names(knitr ::: auto_exts)
。 除了这些设备之外,您还可以提供一个字符串,该字符串是形式为function(文件名,宽度,高度)的函数的名称。 图像大小的单位始终是英寸(即使对于位图设备,其中DPI用于在像素和英寸之间进行转换)。
The chunk options `dev`, `fig.ext`, `fig.width`, `fig.height`, and `dpi` can be vectors (shorter ones will be recycled), e.g., `dev = c('pdf', 'png')` creates a `PDF` and a `PNG`file for the same plot.201 / 5000。dev,fig.ext,fig.width,fig.height和dpi的块选项可以是向量(较短的将被回收),例如dev = c('pdf' ,'png')`为同一图创建一个PDF文件和一个PNG文件。
dev.args
: (NULL
; list) More arguments to be passed to the device, e.g.,dev.args = list(bg = 'yellow', pointsize = 10)
fordev = 'png'
. This option depends on the specific device (see the device documentation). Whendev
contains multiple devices,dev.args
can be a list of lists of arguments, and each list of arguments is passed to each individual device, e.g.,dev = c('pdf', 'tiff'), dev.args = list(pdf = list(colormodel = 'cmyk', useDingats = TRUE), tiff = list(compression = 'lzw'))
.dev.args:(
NULL; list)更多的参数要传递给设备,例如,
dev.args = list(bg ='yellow',pointssize = 10)。 此选项取决于特定的设备(请参阅设备文档)。 当
dev包含多个设备时,
dev.args可以是参数列表的列表,并且每个参数列表都传递给每个单独的设备,例如,
dev = c('pdf','tiff'), dev.args = list(pdf = list(颜色模型='cmyk',useDingats = TRUE),tiff = list(压缩='lzw'))`fig.ext
: (NULL
; character) File extension of the figure output. IfNULL
, it will be derived from the graphical device; seeknitr:::auto_exts
for details.fig.ext
:(NULL
;字符)图形输出的文件扩展名。 如果为NULL,它将从图形设备派生; 有关详细信息,请参见knitr ::: auto_exts
。dpi
: (72
; numeric) The DPI (dots per inch) for bitmap devices (dpi * inches = pixels
).72;数字)位图设备的DPI(每英寸点数)(dpi *英寸=像素)。fig.width
,fig.height
: (both are7
; numeric) Width and height of the plot (in inches), to be used in the graphics device.
图片的高度和宽度,英寸fig.asp
: (NULL
; numeric) The aspect ratio of the plot, i.e., the ratio of height/width. Whenfig.asp
is specified, the height of a plot (the chunk optionfig.height
) is calculated fromfig.width * fig.asp
.
宽高比。(NULL
;数字)绘图的长宽比,即高/宽比。 当指定fig.asp
时,图的高度(fig.height块选项)是从fig.width * fig.asp
中计算出来的。fig.dim
: (NULL
; numeric) A numeric vector of length 2 to providefig.width
andfig.height
, e.g.,fig.dim = c(5, 7)
is a shorthand offig.width = 5, fig.height = 7
. If bothfig.asp
andfig.dim
are provided,fig.asp
will be ignored (with a warning).
(NULL
;数字)一个长度为2的数字向量,以提供fig.width
和fig.height
,例如fig.dim = c(5,7)
是简写形式 图宽度= 5,图高度= 7。 如果同时提供了fig.asp
和fig.dim
,则fig.asp
将被忽略(带有警告)。out.width
,out.height
: (NULL
; character) Width and height of the plot in the output document, which can be different with its physicalfig.width
andfig.height
, i.e., plots can be scaled in the output document. Depending on the output format, these two options can take special values. For example, for LaTeX output, they can be.8\\linewidth
,3in
, or8cm
; for HTML, they may be300px
. For.Rnw
documents, the default value forout.width
will be changed to\\maxwidth
, which is defined on this page. It can also be a percentage, e.g.,'40%'
will be translated to0.4\linewidth
when the output format is LaTeX.
(NULL
;字符)输出文档中绘图的宽度和高度,可以与它的物理fig.width
和fig.height
不同,即 ,可以在输出文档中缩放绘图。 根据输出格式,这两个选项可以采用特殊值。 例如,对于LaTeX输出,它们可以是.8 \ linewidth,3in或8cm; 对于HTML,它们可能是300px。 对于.Rnw文档,out.width的默认值将更改为\ maxwidth,此值在此页面上定义。](https://yihui.org/knitr/demo/framed/ )也可以是一个百分比,例如,当输出格式为LaTeX时,40%''将转换为
0.4 \ linewidth''。out.extra
: (NULL
; character) Extra options for figures. It can be an arbitrary string, to be inserted in\includegraphics[]
in LaTeX output (e.g.,out.extra = 'angle=90'
to rotate the figure by 90 degrees), or<img />
in HTML output (e.g.,out.extra = 'style="border:5px solid orange;"'
).(NULL
;字符)数字的额外选项。 它可以是任意字符串,可以插入LaTeX输出的\ includegraphics []中(例如,out.extra ='angle = 90'将图形旋转90度),或<img />` 在HTML输出中(例如,out.extra ='style =“ border:5px实心橙色;”')。fig.retina
: (1
; numeric) This option only applies to HTML output. For Retina displays, setting this option to a ratio (usually 2) will change the chunk optiondpi
todpi * fig.retina
, andout.width
tofig.width * dpi / fig.retina
internally. For example, the physical size of an image is doubled, and its display size is halved whenfig.retina = fig.retina
:
(1; 数字)此选项仅适用于HTML输出。 对于[Retina显示器,](http://en.wikipedia.org/wiki/Retina_Display)将此选项设置为比率(通常为2)将将dpi''更改为
dpi * fig.retina'',然后 在内部将图宽到图宽 dpi /图视网膜。 例如,当fig.retina = 2
时,图像的物理尺寸增加了一倍,显示尺寸减半。resize.width
,resize.height
: (NULL
; character) The width and height to be used in\resizebox{}{}
in LaTeX output. These two options are not needed unless you want to resize TikZ graphics, because there is no natural way to do it. However, according to the tikzDevice authors, TikZ graphics are not meant to be resized, to maintain consistency in style with other text in LaTeX. If only one of them isNULL
,!
will be used (read the documentation of graphicx if you do not understand this).
resize.width,resize.height
:(NULL
;字符)LaTeX输出中\ resizebox {} {}中要使用的宽度和高度。 除非您想要调整TikZ图形的大小,否则不需要这两个选项,因为没有自然的方法可以做到这一点。 但是,据tikzDevice 的作者称,TikZ图形并非要调整大小,以保持与LaTeX中其他文本的样式一致性。 如果其中只有一个为``NULL'',则将使用!!(如果您不了解,请阅读 graphicx **的文档)。fig.align
: ('default'
; character) Alignment of figures in the output document. Possible values aredefault
,left
,right
, andcenter
. The default is not to make any alignment adjustments.
(`'default';; character)输出文档中图形的对齐。 可能的值为“默认”,“左”,“右”和“中心”。 默认设置是不进行任何对齐调整fig.link
: (NULL
; character) A link to be added onto the figure.fig.env
: ('figure'
; character) The LaTeX environment for figures, e.g., you may setfig.env = 'marginfigure'
to get\begin{marginfigure}
. This option requiresfig.cap
be specified.fig.cap
: (NULL
; character) A figure caption.fig.alt
: (NULL
; character) The alternative text to be used in thealt
attribute of the<img>
tags of figures in HTML output. By default, the chunk optionfig.cap
will be used as the alternative text if provided.fig.scap
: (NULL
; character) A short caption. This option is only meaningful to LaTeX output. A short caption is inserted in\caption[]
, and usually displayed in the “List of Figures” of a PDF document.fig.lp
: ('fig:'
; character) A label prefix for the figure label to be inserted in\label{}
. The actual label is made by concatenating this prefix and the chunk label, e.g., the figure label for ````{r, foo-plot}will be
fig:foo-plotby default. lable{}中可以插入图形标签的前缀。 实际的标签是通过该前缀和块标签制成的,例如,{r,foo-plot}的图形标签默认情况下将为
fig:foo-plot`。fig.pos
: (''
; character) A character string for the figure position arrangement to be used in\begin{figure}[]
.fig.subcap
: (NULL
) Captions for subfigures. When there are multiple plots in a chunk, and neitherfig.subcap
norfig.cap
isNULL
,\subfloat{}
will be used for individual plots (you need to add\usepackage{subfig}
in the preamble). See 067-graphics-options.Rnw for an example.fig.ncol
: (NULL
; integer) The number of columns of subfigures; see this issue for examples (note thatfig.ncol
andfig.sep
only work for LaTeX output).fig.sep
: (NULL
; character) A character vector of separators to be inserted among subfigures. Whenfig.ncol
is specified,fig.sep
defaults to a character vector of which every N-th element is\newline
(whereN
is the number of columns), e.g.,fig.ncol = 2
meansfig.sep = c('', '', '\\newline', '', '', '\\newline', '', ...)
.fig.process
: (NULL
; function) A function to post-process figure files. It should take the path of a figure file, and return the (new) path of the figure to be inserted in the output. If the function contains theoptions
argument, the list of chunk options will be passed to this argument.fig.showtext
: (NULL
; logical) IfTRUE
, callshowtext::showtext_begin()
before drawing plots. See the documentation of the showtext package for details.external
: (TRUE
; logical) Whether to externalize tikz graphics (pre-compile tikz graphics to PDF). It is only used for thetikz()
device in the tikzDevice package (i.e., whendev='tikz'
), and it can save time for LaTeX compilation.sanitize
: (FALSE
; character) Whether to sanitize tikz graphics (escape special LaTeX characters). See the documentation of the tikzDevice package.
There are two hidden options that are not designed to be set by users: fig.cur
(the current figure number or index when there are multiple figures), and fig.num
(the total number of figures in a chunk). The purpose of these two options is to help knitr deal with the filenames of multiple figures as well as animations. In some cases, we can make use of them to write animations into the output using plot files that are saved manually (see the graphics manual for examples).
Animation
interval
: (1
; numeric) Time interval (number of seconds) between animation frames.默认为1秒,动画帧之间的时间间隔(秒数)animation.hook
: (knitr::hook_ffmpeg_html
; function or character) A hook function to create animations in HTML output; the default hook uses FFmpeg to convert images to a WebM video.(默认为knitr :: hook_ffmpeg_html
;函数或字符)用于在HTML输出中创建动画的钩子函数; 默认挂钩使用FFmpeg将图像转换为WebM视频。
- Another hook function is
knitr::hook_gifski
based on the gifski package to create GIF animations.另一个挂钩函数是基于** gifski **包的knitr :: hook_gifski`来创建GIF动画。
This option can also take a character string
'ffmpeg'
or'gifski'
as a shorthand of the corresponding hook function, e.g.,animation.hook = 'gifski'
meansanimation.hook = knitr::hook_gifski
.此选项还可以将字符串'ffmpeg'
或'gifski'作为对应的钩子函数的简写,例如,animation.hook ='gifski'意味着animation.hook = knitr :: hook_gifski 。aniopts
: ('controls,loop'
; character) Extra options for animations; see the documentation of the LaTeX animate package.
ffmpeg.bitrate
(1M
; character) To be passed to the-b:v
argument of FFmpeg to control the quality of WebM videos.动画的额外选项; 请参阅LaTeX ** animate **软件包的文档ffmpeg.format
(webm
; character) The video format of FFmpeg, i.e., the filename extension of the video.webm
; character)FFmpeg的视频格式,即视频的文件扩展名。
@[toc]( <center> knitr翻译03)
title: "Untitled"
author: "ks_c"
date: "2021/2/1"
output: html_document
- Code chunk #代码块
- Child documents #子文件(?)
- Language engines #语言引擎
- Option templates #选项模板
- Extracting source code #提取源码
- Other chunk options # 其他设置
- Package Options # 包的设置
Code chunk
code
: (NULL
; character) If provided, it will override the code in the current chunk. This allows us to programmatically insert code into the current chunk. For example,code = readLines('test.R')
will use the content of the filetest.R
as the code for the current chunk.
(NULL
;字符)如果提供,它将覆盖当前块中的代码。 这使我们能够以编程方式将代码插入当前块中。 例如,code = readLines('test.R')将使用test.R文件的内容作为当前块的代码。ref.label
: (NULL
; character) A character vector of labels of the chunks from which the code of the current chunk is inherited (see the demo for chunk references).
(NULL
; character)当前块代码是来自哪个块的标签,字符向量
Child documents
-
child
: (NULL
; character) A character vector of paths of child documents to be knitted and input into the main document.子文件夹输出到哪里的路径
Language engines
engine
: ('R'
; character) The language name of the code chunk. Possible values can be found innames(knitr::knit_engines$get())
, e.g.,python
,sql
,julia
,bash
, andc
, etc. The objectknitr::knit_engines
can be used to set up engines for other languages.
当前代码块的语言名称,比如python、sql、julia、c等-
engine.path
: (NULL
; character) The path to the executable of theengine
. This option makes it possible to use alternative executables in your system, e.g., the defaultpython
may be at/usr/bin/python
, and you may setengine.path = '~/anaconda/bin/python'
to use a different version of Python.
引擎的路径。 此选项使您可以在系统中使用其他可执行文件,例如,默认的python
可能位于/ usr / bin / python中,并且您可以设置
engine.path ='〜/ anaconda / bin / python' 使用其他版本的Python。engine.path
can also be a list of paths, which makes it possible to set different engine paths for different engines, e.g.,也可以同时为不同的引擎设置不同的路径。
knitr::opts_chunk$set(engine.path = list(
python = '~/anaconda/bin/python',
ruby = '/usr/local/bin/ruby'
))
The names of the list correspond to the names of the engines.
Option templates
opts.label: (NULL; character) The label of options set in knitr::opts_template (see ?knitr::opts_template). This option can save some typing effort for sets of frequently used chunk options.
Extracting source code
purl: (TRUE; logical) When running knitr::purl() to extract source code from a source document, whether to include or exclude a certain code chunk.
Other chunk options
R.options: (NULL; list) Local R options for a code chunk. These options are set temporarily via options() before the code chunk, and restored after the chunk.