> 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/texlive/zh-cn/ji-qiao/r-dai-ma-knitr.md).

# R 代码（knitr）

Overleaf 提供了与 **knitr**的集成，允许你在 LaTeX 文档中添加 R 代码以生成动态输出。

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

{% code overflow="wrap" %}

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

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

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

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

@
\end{document}
```

{% endcode %}

![KnitrDemo1.png](https://3502988919-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVetOkhFZmAC8QCQK0Pi7%2Fuploads%2F4rB1ItV9jgLU4dT6o3Hf%2FKnitrDemo1.png?alt=media\&token=5b2d4df8-8de9-4bdd-be61-0a3992026edf)

[在 Overleaf 上打开这个 `knitr` 示例](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 中设置一些额外选项。见下例：

{% code overflow="wrap" %}

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

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

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

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

@
\end{document}
```

{% endcode %}

![KnitrDemo2.png](https://3502988919-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVetOkhFZmAC8QCQK0Pi7%2Fuploads%2FHtobrK1TjY4SG4ax2BH5%2FScreenshot%202025-12-16%20143420.png?alt=media\&token=50675660-f20f-44d3-be60-fb91b8dbd255)

[在 Overleaf 上打开这个 `knitr` 示例](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

  <div data-gb-custom-block data-tag="hint" data-style="info" class="hint hint-info"><p><em>如果将 cache 设置为 true，则该 chunk 不会运行，只会使用它生成的对象。如果该 chunk 中的数据没有更改，这可以节省时间。</em></p></div>

注意，Overleaf 目前不支持 cache=TRUE 选项，但在本地应该可以工作。 [参见](https://learn.overleaf.com/learn/Knitr#Reference_guide) 参考指南

### 以获取更多选项。

内联命令

{% code overflow="wrap" %}

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

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

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

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

@

可以访问在 chunk 中生成的对象并将它们内联打印。
\end{document}
```

{% endcode %}

![因此，数据的均值是 $\Sexpr{mean(X)}$](https://3502988919-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVetOkhFZmAC8QCQK0Pi7%2Fuploads%2Fbyz9VKDCCPcoWHbznSJ4%2FScreenshot%202025-12-16%20143647.png?alt=media\&token=9d5ef4de-f413-4bf2-83c8-bf2171f50dee)

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

KnitrDemo3.png `命令` \Sexpr{mean(X)} `打印由 R 代码返回的输出`mean(X)

### 。在大括号内可以传入任何 R 命令。

图表

{% code overflow="wrap" %}

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

图表也可以添加到 knitr 文档中，如下示例：

<<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")

\end{document}
```

{% endcode %}

![图 \ref{fig:plot1} 是一个简单的直方图。](https://3502988919-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVetOkhFZmAC8QCQK0Pi7%2Fuploads%2F5NI4NOJICjnYf8Z2Me1b%2FScreenshot%202025-12-16%20143811.png?alt=media\&token=d937786f-da22-4cbd-9adf-f277ec9f77c4)

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

KnitrDemo4.png

`该直方图使用存储在当前工作目录下 "data.txt" 中的数据。向该 chunk 传递了一些与图形相关的选项。`plot1 `这是用于引用该图的标签。前缀 "fig:" 是强制性的。你可以在示例中看到该图是用`.`\ref{fig:plot1}` 引用的。 [fig.pos="t"](https://learn.overleaf.com/learn/Positioning_images_and_tables#The_figure_environment).`定位参数。这与`figure 环境中使用的相同`fig.height=4, fig.width=4`图形的宽度和高度。

### fig.cap="First plot"

图的标题（Caption）。

外部 R 脚本 `你可以将外部 R 脚本的部分内容导入到 knitr 文档中。这很有用，因为通常会在将脚本包含到文档之前在外部程序中编写和调试脚本。` 假设我们在一个名为以下文件中有如下 R 代码

```r
mycode.R
# 创建一个数列
 X = 2:10

我们将其包含在 LaTeX 文档中：
# 显示基本统计量
summary(X)
```

\## ---- myrcode1

```r
mycode.R
```

和

```r
我们将其包含在 LaTeX 文档中：
```

\## ---- myrcode2

```r
注意这些行：

这些标记了代码块的开始，如果你想在文档中使用该脚本则是强制性的，如下面的代码片段所示：
下面的 chunk 不会被打印
@

<<echo=FALSE, cache=FALSE>>=

read_chunk("mycode.R")

@
```

![代码必须出现在这里](https://3502988919-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVetOkhFZmAC8QCQK0Pi7%2Fuploads%2FPzKSGsFTMdhs9K8dE8Ny%2FKnitrDemo5.png?alt=media\&token=9c32c381-7621-4b7d-9d73-c1e7a0b6aac8)

<\<myrcode2>>= `下面的 chunk 不会被打印` KnitrDemo5.png `中传递了两个附加选项` 第一个 chunk 不会被打印，仅用于使用命令导入脚本 `## ----`。这就是为什么选项 `被设置的原因。另外，脚本不能被缓存。一旦脚本被导入，你可以使用在`.

之后设置的标签来打印一个 chunk。 [在这种情况下它是](https://www.overleaf.com/project/new/template/20429?id=69894649\&templateName=Knitr+full+demo\&latexEngine=pdflatex\&texImage=texlive-full%3A2020.1\&mainFile=) .

### myrcode2

我们已将所有文章代码片段放入一个项目，

* `你可以在 Overleaf 上打开`参考指南
  * `一些 chunk 选项：` results
  * `。更改 R 代码生成的结果行为。可能的值有：` markup
  * `使用 LaTeX 来格式化输出。` asis
  * `打印 R 的原始结果。` hold
* `将输出结果保留并推到 chunk 的末尾。`hide
  * `隐藏结果。` echo
  * `。是否包含 R 源代码。其他参数包括：` echo=2:3
* `仅打印第二行和第三行；`echo=-2:-3 `仅排除第二行和第三行。` 和 `cache`
* `。是否缓存代码块。可能的值有：`TRUE `仅排除第二行和第三行。` 和 `cache`
* `FALSE`highlight *。是否对源代码进行高亮。可能的值有：*.


---

# 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/texlive/zh-cn/ji-qiao/r-dai-ma-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.
