> 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/ja/sononotopikku/29-knitr.md).

# Knitr

Wikipedia で述べられているように、 [Knitr は R による動的レポート生成のためのエンジンです](https://en.wikipedia.org/wiki/Knitr)、統計指向のプログラミング言語です。この記事では、動的な出力を生成するために LaTeX 文書に R コードを追加する方法を説明します。

標準的な LaTeX ディストリビューションでは、OS 上で R をセットアップし、コンパイルするためにいくつかの特別なコマンドを実行する必要があります。Overleaf ならその手間を省けます、 **knitr** そのままで動作します。

## はじめに

R コードを含む文書は、拡張子 `.Rtex` または `.Rnw`、そうしないとコードは動作しません。例を見てみましょう：

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

処理され、その出力が文書に含められる R コマンドを、あなたの \LaTeX{} 文書に記述できます：

<<>>=
# 数列を作成する
X = 2:10

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

@
\end{document}
```

![KnitrDemo1.png](/files/45ecfc701235fcd7da5007ffbd43fab8bf740d4c)

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

処理され、その出力が文書に含められる R コマンドを、あなたの \LaTeX{} 文書に記述できます：

<<echo=FALSE, cache=TRUE>>=
# 数列を作成する
X = 2:10

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

@
\end{document}
```

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

&#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=)

内部で渡される追加オプションは 3 つあります `<<` と `>>`.

**echo=FALSE**

これによりコードは隠され、R が生成した出力のみが表示されます。

**cache=TRUE**

cache を true に設定すると、そのチャンクは実行されず、そのチャンクによって生成されたオブジェクトだけが使われます。これは、そのチャンク内のデータが変更されていない場合に時間を節約します。なお、cache=TRUE オプションは現在 Overleaf ではサポートされていませんが、ローカルでは動作するはずです。

参照: [リファレンスガイド](#reference-guide) その他のオプションについて。

## インラインコマンド

チャンクで生成されたオブジェクトにアクセスし、インラインで表示することができます。

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

処理され、その出力が文書に含められる R コマンドを、あなたの \LaTeX{} 文書に記述できます：

<<echo=FALSE, cache=TRUE>>=
# 数列を作成する
X = 2:10

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

@

したがって、データの平均は $\Sexpr{mean(X)}$
\end{document}
```

![KnitrDemo3.png](/files/80a8734fda8ce4725d9265c8faff958894e43bcb)

&#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="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/c09bfea6b8403c7634d628705b885fe1935af7fb)

&#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="First plot"**

図のキャプション。

## 外部 R スクリプト

外部 R スクリプトの一部を **knitr** 文書へ取り込むことができます。これは、文書に含める前に外部プログラムでスクリプトを書いてデバッグすることがかなり一般的なので、とても便利です。

次の R コードが、 `mycode.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/baf68a44e3118284511fe4b7e03489c5925f28d8)

最初のチャンクは表示されず、コマンド `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` 2 行目と 3 行目のみを表示します; `echo=-2:-3` 2 行目と 3 行目だけを除外します。
* `cache`。コードチャンクをキャッシュするかどうか。取りうる値は `TRUE` と `FALSE`
* `highlight`。ソースコードを強調表示するかどうか。取りうる値は `TRUE` と `FALSE`
* `background`。チャンクの背景色。rgb および HTML 形式を使用でき、既定値は *"#F7F7F7"*.

## 参考文献

詳しくは次を参照してください。

* [minted を使ったコードの強調表示](/latex/ja/shu-shi-she-ding/12-code-highlighting-with-minted.md)
* [LaTeX で色を使う](/latex/ja/shu-shi-she-ding/13-using-colors-in-latex.md)
* [LaTeX におけるプロット](/latex/ja/fen-ye-bie/08-pgfplots-package.md)
* [画像の挿入](/latex/ja/sononotopikku/27-inserting-images.md)
* [表](/latex/ja/to/01-tables.md)
* [画像と表の配置](/latex/ja/to/02-positioning-images-and-tables.md)
* [TikZ パッケージ](/latex/ja/to/05-tikz-package.md)
* [数学表現](/latex/ja/shu-xue/01-mathematical-expressions.md)
* [その **knitr** Web ページ](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/ja/sononotopikku/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.
