> 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-tw/geng-duo-zhu-ti/29-knitr.md).

# Knitr

如 Wikipedia 所述， [Knitr 是一個用 R 進行動態報告生成的引擎](https://en.wikipedia.org/wiki/Knitr)，R 是一種以統計為導向的程式語言。本文說明如何將 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/c966a39f9ae124267292f8accd4ebf67b86378df)

&#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 程式碼，這段程式碼及其輸出會以類似清單的格式列印出來。這個程式碼區塊可以加入一些額外參數來自訂動態輸出。請見下一節。

## 程式碼區塊

前一節所示的程式碼區塊通常稱為一個 *區塊*。你可以在 knitr 區塊中設定一些額外選項。請見下方範例：

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

你可以在 \LaTeX{} 文件中輸入 R 指令，系統會處理它們，並將輸出內容包含到文件中：

<<echo=FALSE, cache=TRUE>>=
# 建立一個數字序列
X = 2:10

# 顯示基本統計量
summary(X)

@
\end{document}
```

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

&#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**

如果將快取設為 true，這個區塊就不會執行，只會執行由它產生的物件。若該區塊中的資料未變更，這可節省時間。請注意，目前 Overleaf 尚不支援 cache=TRUE 選項，但在本機應該可以運作。

請參閱 [參考指南](#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/cbd2614858e24fb07e501e4a2fe4567435edf4e8)

&#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="第一個圖表">>=

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

hist(xdata$data, main="Overleaf 直方圖", xlab="資料")

@

圖 \ref{fig:plot1} 是一個簡單的直方圖。

\end{document}
```

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

&#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」內的資料。此區塊傳入了幾個與圖表相關的選項。

**plot1**

這是用來參照該圖的標籤。前綴「fig:」是必須的。你可以在範例中看到，該圖是透過 \ref{fig:plot1} 來參照。

**fig.pos="t"**

定位參數。這與 figure 環境中使用的相同。

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

圖的寬度與高度。

**fig.cap="第一個圖表"**

圖說。

## 外部 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/f47ddc1a7234960b893d7d7ac4dcd906d61ba06e)

第一個區塊不會被列印，只會用來透過指令匯入指令碼 `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-tw/ge-shi-hua/12-code-highlighting-with-minted.md)
* [在 LaTeX 中使用顏色](/latex/zh-tw/ge-shi-hua/13-using-colors-in-latex.md)
* [LaTeX 中的圖表](/latex/zh-tw/te-ding-ling-yu/08-pgfplots-package.md)
* [插入圖片](/latex/zh-tw/geng-duo-zhu-ti/27-inserting-images.md)
* [表格](/latex/zh-tw/tu-biao-yu-biao-ge/01-tables.md)
* [圖片與表格的定位](/latex/zh-tw/tu-biao-yu-biao-ge/02-positioning-images-and-tables.md)
* [TikZ 套件](/latex/zh-tw/tu-biao-yu-biao-ge/05-tikz-package.md)
* [數學表達式](/latex/zh-tw/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-tw/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.
