> 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/texlive/zh-tw/ji-neng/r-cheng-shi-ma-knitr.md).

# R 程式碼（knitr）

Overleaf 提供與 **knitr**，它可讓您將 R 程式碼加入您的 LaTeX 文件，以產生動態輸出。

含有 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)

[開啟這個 `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 區塊中設定一些額外選項。請看下面的範例：

{% 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)

[開啟這個 `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，則不會執行該區塊，只會使用其產生的物件。若該區塊中的資料沒有變更，這可節省時間。

  <div data-gb-custom-block data-tag="hint" data-style="info" class="hint hint-info"><p><em>請注意，cache=TRUE 選項目前不支援 Overleaf，但在本機應可正常運作。</em></p></div>

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

@

因此，資料的平均值是 $\Sexpr{mean(X)}$
\end{document}
```

{% endcode %}

![KnitrDemo3.png](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)

[開啟這個 `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 文件中，如此範例所示：

{% code overflow="wrap" %}

```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}
```

{% endcode %}

![KnitrDemo4.png](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)

[開啟這個 `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"` 位置參數。這與 [圖形環境](https://learn.overleaf.com/learn/Positioning_images_and_tables#The_figure_environment).`fig.height=4, fig.width=4`圖形寬度與高度。`fig.cap="第一個圖"`圖說。

### 外部 R 腳本

您可以將外部 R 腳本的一部分匯入 knitr 文件。這非常有幫助，因為在將腳本加入文件之前，通常先在外部程式中撰寫並除錯是很常見的。

假設我們在一個名為 `mycode.R` 的檔案中有以下 R 程式碼，我們將其包含在 LaTeX 文件中：

```r
## ---- myrcode1
# 建立一個數列
 X = 2:10

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

請注意這些行：

```r
## ---- myrcode1
```

和

```r
## ---- myrcode2
```

這些標示了程式碼區塊的開頭；如果您想在文件中使用此腳本，這些是必須的，如下列程式碼片段所示：

```r
下方的區塊不會被列印

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

程式碼必須顯示在這裡

<<myrcode2>>=

@
```

![KnitrDemo5.png](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)

第一個區塊不會列印，僅用來透過命令 `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"*.


---

# 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/texlive/zh-tw/ji-neng/r-cheng-shi-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.
