> For the complete documentation index, see [llms.txt](https://ayakaleaf-pro.ayaka.space/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://ayakaleaf-pro.ayaka.space/latex/zh-cn/geng-duo-zhu-ti/29-knitr.md).

# Knitr

正如维基百科所述， [Knitr 是一个用于使用 R 动态生成报告的引擎](https://en.wikipedia.org/wiki/Knitr)，一种面向统计的编程语言。本文将说明如何将 R 代码添加到你的 LaTeX 文档中以生成动态输出。

在标准的 LaTeX 发行版中，你必须在操作系统中配置好 R，并运行一些特殊命令来编译它。Overleaf 可以帮你省去这些麻烦， **knitr** 开箱即用。

## 引言

包含 R 代码的文档必须保存为扩展名 `.Rtex` 或 `.Rnw`，否则代码将无法工作。让我们来看一个示例：

```latex
\documentclass{article}
\begin{document}

你可以在你的 \LaTeX{} 文档中输入 R 命令，这些命令将被处理，其输出也会包含在文档中：

<<>>=
# 创建一个数字序列
X = 2:10

# 显示基本统计量
summary(X)

@
\end{document}
```

![KnitrDemo1.png](/files/76f218c7d02cc4fc8dd95781279f9b0b68ce2df1)

&#x20;[打开此 `knitr` Overleaf 上的示例](https://www.overleaf.com/project/new/template/20421?id=69881107\&templateName=Knitr+demo+1\&latexEngine=pdflatex\&texImage=texlive-full%3A2020.1\&mainFile=)

如你所见，字符之间的文本 `<<>>=` 和 `@` 是 R 代码，这段代码及其输出会以类似清单的格式打印出来。这个代码块还可以接受一些额外参数来自定义动态输出。参见下一节。

## 代码块

上一节中展示的那样的代码块通常称为一个 *chunk*。你可以在 knitr 的 chunk 中设置一些额外选项。请看下面的示例：

```latex
\documentclass{article}
\begin{document}

你可以在你的 \LaTeX{} 文档中输入 R 命令，这些命令将被处理，其输出也会包含在文档中：

<<echo=FALSE, cache=TRUE>>=
# 创建一个数字序列
X = 2:10

# 显示基本统计量
summary(X)

@
\end{document}
```

![KnitrDemo2.png](/files/e40949a3ad5194733cd1c983d874c178ba9ead6d)

&#x20;[打开此 `knitr` Overleaf 上的示例](https://www.overleaf.com/project/new/template/20423?id=69885763\&templateName=Knitr+demo+2\&latexEngine=pdflatex\&texImage=texlive-full%3A2020.1\&mainFile=)

其中传入了三个额外选项 `<<` 和 `>>`.

**echo=FALSE**

这会隐藏代码，只打印 R 生成的输出。

**cache=TRUE**

如果将 cache 设为 true，则不会运行该 chunk，只会使用它生成的对象。如果该 chunk 中的数据没有变化，这可以节省时间。请注意，Overleaf 目前不支持 cache=TRUE 选项，但它在本地应该可以工作。

请参见 [参考指南](#reference-guide) 以查看更多选项。

## 行内命令

可以访问在 chunk 中生成的对象，并将它们以内联方式打印出来。

```latex
\documentclass{article}
\begin{document}

你可以在你的 \LaTeX{} 文档中输入 R 命令，这些命令将被处理，其输出也会包含在文档中：

<<echo=FALSE, cache=TRUE>>=
# 创建一个数字序列
X = 2:10

# 显示基本统计量
summary(X)

@

因此，数据的均值是 $\Sexpr{mean(X)}$
\end{document}
```

![KnitrDemo3.png](/files/0ac5ee4d35fd711467b0c480a63b4b9d3854a765)

&#x20;[打开此 `knitr` Overleaf 上的示例](https://www.overleaf.com/project/new/template/20425?id=69886866\&templateName=Knitr+demo+3\&latexEngine=pdflatex\&texImage=texlive-full%3A2020.1\&mainFile=)

命令 `\Sexpr{mean(X)}` 会打印由 R 代码返回的输出 `mean(X)`。在花括号中可以传入任何 R 命令。

## 图形

图形也可以添加到一个 **knitr** 文档中。请看下一个示例

```latex
\documentclass{article}
\begin{document}

<<plot1, fig.pos="t", fig.height=4, fig.width=4, fig.cap="First plot">>=

xdata = read.csv(file="data.txt", head=TRUE,sep=" ")

hist(xdata$data, main="Overleaf histogram", xlab="Data")

@

图 \ref{fig:plot1} 是一个简单的直方图。

\end{document}
```

![KnitrDemo4.png](/files/b79a9ce12a89e55bc59dc8c3cdb27ddfbe5906ef)

&#x20;[打开此 `knitr` Overleaf 上的示例](https://www.overleaf.com/project/new/template/20427?id=69890965\&templateName=Knitr+demo+3\&latexEngine=pdflatex\&texImage=texlive-full%3A2020.1\&mainFile=)

这个直方图使用存储在当前工作目录中的 “data.txt” 里的数据。若干与图形相关的选项被传入该 chunk。

**plot1**

这是用于引用该图的标签。前缀 “fig:” 是必需的。你可以在示例中看到该图是通过 \ref{fig:plot1} 引用的。

**fig.pos="t"**

位置参数。这与 figure 环境中使用的参数相同。

**fig.height=4, fig.width=4**

图形的宽度和高度。

**fig.cap="First plot"**

图形标题。

## 外部 R 脚本

你可以将外部 R 脚本的部分内容导入到一个 **knitr** 文档中。这非常有帮助，因为在将脚本包含到文档之前，先在外部程序中编写和调试脚本是很常见的。

假设我们在一个名为 `mycode.R` 的文件中有以下 R 代码，我们将其包含到我们的 LaTeX 文档中：

```latex
## ---- myrcode1
# 创建一个数字序列
 X = 2:10

## ---- myrcode2
# 显示基本统计量
summary(X)
```

注意这些行

```latex
## ---- myrcode1
```

和

```latex
## ---- myrcode2
```

这些行标记了一个代码块的开始；如果你想在文档中使用这个脚本，它们是必需的，如下面的代码片段所示：

```latex
下面的 chunk 不会被打印

<<echo=FALSE, cache=FALSE>>=
read_chunk("mycode.R")
@

代码必须显示在这里

<<myrcode2>>=

@
```

![KnitrDemo5.png](/files/1133dbb470886888efdb9462b457be5732231b3c)

第一个 chunk 不会打印，只用于通过命令 `read_chunk("mycode.R")`，这就是为什么选项 `echo=FALSE` 被设置。并且脚本不能被缓存。脚本导入后，你可以使用在后面设置的标签来打印一个 chunk `## ----`。在这种情况下，它是 `myrcode2`.

我们已经把本文的所有代码片段放入了一个项目中，你可以  [在 Overleaf 上打开](https://www.overleaf.com/project/new/template/20429?id=69894649\&templateName=Knitr+full+demo\&latexEngine=pdflatex\&texImage=texlive-full%3A2020.1\&mainFile=) .

## 参考指南

**一些 chunk 选项**

* `结果`。改变 R 代码生成结果的行为，可选值有
  * `markup` 使用 LaTeX 来格式化输出。
  * `asis` 打印来自 R 的原始结果。
  * `hold` 将输出结果保留，并在 chunk 结束时统一输出。
  * `hide` 隐藏结果。
* `echo`。是否包含 R 源代码。还可以接受其他参数， `echo=2:3` 只打印第二和第三行； `echo=-2:-3` 只排除第二和第三行。
* `cache`。是否缓存该代码块。可选值有 `TRUE` 和 `FALSE`
* `highlight`。是否高亮源代码。可选值有 `TRUE` 和 `FALSE`
* `background`。该 chunk 的背景颜色，可使用 rgb 和 HTML 格式，默认值为 *"#F7F7F7"*.

## 进一步阅读

更多信息请参见

* [使用 minted 的代码高亮](/latex/zh-cn/ge-shi-hua/12-code-highlighting-with-minted.md)
* [在 LaTeX 中使用颜色](/latex/zh-cn/ge-shi-hua/13-using-colors-in-latex.md)
* [LaTeX 中的图形](/latex/zh-cn/te-ding-ling-yu/08-pgfplots-package.md)
* [插入图片](/latex/zh-cn/geng-duo-zhu-ti/27-inserting-images.md)
* [表格](/latex/zh-cn/tu-xing-he-biao-ge/01-tables.md)
* [图片和表格的定位](/latex/zh-cn/tu-xing-he-biao-ge/02-positioning-images-and-tables.md)
* [TikZ 宏包](/latex/zh-cn/tu-xing-he-biao-ge/05-tikz-package.md)
* [数学表达式](/latex/zh-cn/shu-xue/01-mathematical-expressions.md)
* [该 **knitr** 网页](http://yihui.name/knitr/)
* [该 **knitr** 软件包手册](https://bitbucket.org/stat/knitr/downloads/knitr-manual.pdf)


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://ayakaleaf-pro.ayaka.space/latex/zh-cn/geng-duo-zhu-ti/29-knitr.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
