> For the complete documentation index, see [llms.txt](https://overleaf-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://overleaf-pro.ayaka.space/latex/zh-cn/geng-duo-zhu-ti/29-knitr.md).

# Knitr

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

在标准的 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;[在 Overleaf 中打开此 `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 代码块中设置一些额外选项。见下面的示例：

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

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

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

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

@
\end{document}
```

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

&#x20;[在 Overleaf 中打开此 `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，则不会重新运行该代码块，只使用它生成的对象。若该代码块中的数据没有变化，这样可以节省时间。注意，cache=TRUE 选项目前不受 Overleaf 支持，但在本地应该可以正常工作。

参见 [参考指南](#reference-guide) 了解更多选项。

## 行内命令

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

```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;[在 Overleaf 中打开此 `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;[在 Overleaf 中打开此 `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”里的数据。若干与图形相关的选项被传给了该代码块。

**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
下面的代码块不会被打印

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

代码必须显示在这里

<<myrcode2>>=

@
```

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

第一个代码块不会被打印，它只用于通过命令导入脚本 `read_chunk("mycode.R")`，这就是为什么选项 `echo=FALSE` 被设为该值。此外，脚本不能被缓存。脚本导入后，你可以使用在 `## ----`之后设置的标签来打印一个代码块。在本例中它是 `myrcode2`.

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

## 参考指南

**一些代码块选项**

* `results`。改变由 R 代码生成的结果的行为，可选值有
  * `markup` 使用 LaTeX 格式化输出。
  * `asis` 打印来自 R 的原始结果。
  * `hold` 保留输出结果，并在代码块末尾再输出它们。
  * `hide` 隐藏结果。
* `echo`。是否包含 R 源代码。还可以接受其他参数， `echo=2:3` 只打印第二行和第三行； `echo=-2:-3` 仅排除第二行和第三行。
* `cache`。是否缓存该代码块。可选值有 `TRUE` 和 `FALSE`
* `highlight`。是否高亮源代码。可选值有 `TRUE` 和 `FALSE`
* `background`。代码块的背景颜色，可以使用 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-biao-he-biao-ge/01-tables.md)
* [图片和表格的位置](/latex/zh-cn/tu-biao-he-biao-ge/02-positioning-images-and-tables.md)
* [TikZ 宏包](/latex/zh-cn/tu-biao-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://overleaf-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.
