> 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/ja/sukiru/rkdoknitr.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)

[これを開く `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="First plot">>=

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

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

@

図 \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="First plot"

### 図のキャプション。

外部Rスクリプト

外部のRスクリプトの一部をknitr文書に取り込むことができます。これは、文書に含める前に外部プログラムでスクリプトを書いてデバッグすることがかなり一般的であるため、とても有用です。 `次のRコードがファイルにあると仮定します` mycode.R

```r
をLaTeX文書に含めると：
# 数値の列を作成する
 X = 2:10

## ---- myrcode1
# 基本的な統計量を表示する
summary(X)
```

\## ---- myrcode2

```r
をLaTeX文書に含めると：
```

と

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

次の行に注意してください：

```r
これらはコードチャンクの開始を示すもので、文書でこのスクリプトを使用する場合は必須です。次のコード断片に示すように：

下のチャンクは印字されません
<<echo=FALSE, cache=FALSE>>=
@

read_chunk("mycode.R")

ここにコードが表示されなければなりません

@
```

![<\<myrcode2>>=](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)

KnitrDemo5.png `<<echo=FALSE, cache=FALSE>>=` 最初のチャンクは印字されず、コマンドでスクリプトをインポートするためだけに使用されます `echo=FALSE` 。だからオプション `## ----`が設定されています。また、スクリプトはキャッシュされてはいけません。スクリプトがインポートされたら、で設定したラベルを使ってチャンクを印字できます。 `この場合それは`.

myrcode2 [です。](https://www.overleaf.com/project/new/template/20429?id=69894649\&templateName=Knitr+full+demo\&latexEngine=pdflatex\&texImage=texlive-full%3A2020.1\&mainFile=) .

### すべての記事コード断片をプロジェクトに入れました

あなたはOverleafでこれを開くことができます

* `リファレンスガイド`いくつかのチャンクオプション：
  * `results` 。Rコードによって生成される結果の振る舞いを変更します。可能な値は：
  * `markup` 出力をフォーマットするためにLaTeXを使用します。
  * `asis` Rからの生の結果をそのまま出力します。
  * `hold` 出力結果を保持してチャンクの最後へ送ります。
* `hide`結果を隠します。
  * `echo` 。Rソースコードを含めるかどうか。他のパラメータには：
  * `echo=2:3` は2行目と3行目のみを印字します；
* `echo=-2:-3`は2行目と3行目のみを除外します。 `cache` と `。コードチャンクをキャッシュするかどうか。可能な値は：`
* `TRUE`FALSE `cache` と `。コードチャンクをキャッシュするかどうか。可能な値は：`
* `highlight`。ソースコードをハイライトするかどうか。可能な値は： *background」「t114":"。チャンクの背景色。rgbおよびHTML形式を使用できます。既定値は","t115":"#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://ayakaleaf-pro.ayaka.space/texlive/ja/sukiru/rkdoknitr.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.
