Rの集計、分析結果を Markdown形式で作成するための R Markdown というパッケージが提供されている。
レポートの形式は HTML の他に Word や PDF 等も対応しているが、当記事では HTML の生成についてのみ記載する。
とりあえず rmarkdown と knitr をインストール。
尚、word文書等を作成する場合は pandoc も必要だが、当記事では扱わない為、インストールしない。
install.packages("rmarkdown") install.packages("knitr") install.packages("reticulate") # コードチャンクを python などの他言語で書く場合は必要
Markdown 形式のファイルを拡張子 Rmd で作成し、render するだけ。
※Rmd の記述方法等は後述。
sample.Rmd
--- title: "Sample1" author: "Daisuke.M" date: '`r Sys.time()`' output: html_document --- ```{r include = F, message = F, warning = F} library(knitr) ``` ```{r echo = F} plot(iris$Sepal.Length, iris$Sepal.Width) ```
library(rmarkdown) render("sample.Rmd")
これだけで sample.html が出力される。
Rmd の先頭で --- から --- の間に基本的な設定を YAML形式で記述する。
参考
https://rmarkdown.rstudio.com/lesson-9.html
https://bookdown.org/yihui/rmarkdown/html-document.html
--- title: "Sample1" author: "Daisuke.M" date: '`r Sys.time()`' output: html_document: includes: in_header: header.html before_body: doc_prefix.html after_body: doc_suffix.html ---
コードチャンクにオプションを設定する事で、挙動の微調整ができる。
参考
https://rmarkdown.rstudio.com/lesson-3.html
https://yihui.name/knitr/options/
基本的なオプション
オプション | 説明 |
include | コードの実行結果を出力内容に含めたくない場合は FALSE を指定する |
echo | コード自体を出力内容に含めたくない場合は FALSE を指定する |
message | コード実行時の message による出力を出力内容に含めたくない場合は FALSE を指定する |
warning | コード実行時の warning による出力を出力内容に含めたくない場合は FALSE を指定する |
fig.cap | グラフに付けたいキャプションを指定する(alt属性 及び pタグとして出力される) |
使用例)
## 実行時のコードは出力しない ```{r echo = F} plot(iris$Sepal.Length, iris$Sepal.Width) ``` ## ファイルに出力 ```{r echo = F, include = F} png("plot1.png") plot(iris$Sepal.Length, iris$Sepal.Width) dev.off() ```
前後をバックスラッシュで囲む事によってインラインコードを記述可能。
参考
https://rmarkdown.rstudio.com/lesson-4.html
### 日付を出力 `r Sys.time()`
尚、基本設定の YAML 部分に書く場合は シングルクォートで括る必要がある。
--- : date: '`r Sys.time()`' : ---
Rmd 側で使用する値をパラメータ化しておいて、render 時に呼び出し側から渡す事が出来る。
参考
https://rmarkdown.rstudio.com/lesson-6.html
--- title: "Sample1" params: param1: "blank" output: html_document --- ```{r echo = F} print(params$param1) ```
呼び出し側
library(rmarkdown) render("sample1.Rmd", params = list(param1 = "test12345"))
実行結果
## [1] "test12345"
knitr::kable を使用すると データフレームの内容を HTML 等の表(table)として描画する事ができる。
参考
https://rmarkdown.rstudio.com/lesson-7.html
```{r echo = F} kable(head(iris, 10)) ```
出力が縦長になりすぎる場合などは、タブ化できる。
参考
https://bookdown.org/yihui/rmarkdown/html-document.html#tabbed-sections
### タブの描画 {.tabset} #### Tab1 ```{r echo = F} plot(iris$Sepal.Length, iris$Sepal.Width) ``` #### Tab2 ```{r echo = F} plot(iris$Petal.Length, iris$Petal.Width) ```
基本的な Markdown 記法はそこそこサポートしてる模様。
参考
https://rmarkdown.rstudio.com/lesson-8.html
### Markdown記法 - リスト1 - **AAA** - **BBB** - リスト2 - **CCC** - **DDD** 1. リスト1 - *AAA* - *BBB* 1. リスト2 - *CCC* - *DDD* | col1 | col2 | |:-----|:-----| | val1 | val2 | | val3 | val4 |
python など他の言語でコードチャンクを書くための仕組みが提供されている。
※reticulate が必要。
参考
https://rmarkdown.rstudio.com/lesson-5.html
https://bookdown.org/yihui/rmarkdown/language-engines.html
sample.Rmd
```{r include = F, message = F, warning = F} library(knitr) library(reticulate) ``` ```{python} x = [i for i in range(10)] print(x) ```
使用する python のパスを明示したい場合は、呼び出し側で use_python 、use_virtualenv、use_condaenv 等で設定するか、
コードチャンク側で {python, engine.path = '/usr/bin/python3'} のように指定する事が可能。
例) 呼び出し側で指定する場合
library(rmarkdown) library(knitr) library(reticulate) use_python("/usr/bin/python3") render("sample1.Rmd")
例) コードチャンク側で指定する場合
```{python, engine.path = '/usr/bin/python3'} x = [i for i in range(10)] print(x) ```
基本的に全てのデータは html に内包する形で出力される。
例えば、以下の様にグラフをファイルに出力した後に、img タグを描画した場合でも、
img タグは <img src="plot1.png" /> の様には展開されず、base64 エンコードしたデータが埋め込まれた状態で出力される。
sample1.Rmd
### ファイル出力後に img タグを描画 ```{r echo = F, include = F} png("plot1.png") plot(iris$Sepal.Length, iris$Sepal.Width) dev.off() ``` <!-- imgタグを出力 --> ![](plot1.png)
出力結果
<div id="-img-" class="section level3"> <h3>ファイル出力後に img タグを描画</h3> <!-- imgタグを出力 --> <div class="figure"> <img src="data:image/png;base64,iVBORw0KGg ..." > </div> </div>
これは script タグや css でも同様で、以下の様に記述した場合
<link rel="stylesheet" href="style.css"> <script src="script.js"></script>
style.css
#h1 { color: red; }
script.js
alert("test");
生成されるHTMLは以下の様に css は urlエンコード、js は base64エンコードされた内容が埋め込まれる形となる。
<link href="data:text/css;charset=utf-8,h1%20%7B%0Acolor%3A%20red%3B%0A%7D" rel="stylesheet"> <script src="data:application/x-javascript;base64,YWxlcnQoInRlc3QhIik7"></script>
埋め込まずに出力したい場合は、self_contained = false を指定する。
--- title: "Sample1" author: "Daisuke.M" date: '`r Sys.time()`' output: html_document: self_contained: false --- <link href="data:text/css;charset=utf-8,h1%20%7B%0Acolor%3A%20red%3B%0A%7D" rel="stylesheet"> <script src="data:application/x-javascript;base64,YWxlcnQoInRlc3QhIik7"></script>
生成結果
: <link rel="stylesheet" href="style1.css"> <script src="script1.js"></script>
上記の通り self_contained: false にして出力した結果を見ると、
デフォルトで jquery 等が利用できる状態で出力されている事が分かる。
なので、これらを使用してある程度リッチなコンテンツを作成する事が出来る。(自分で組み込んでも良いが)
※ご丁寧に bootstrap や viewport まで出力されているので、レスポンシブなコンテンツも楽に作成できそう。
<script src="sample1_files/jquery-1.11.3/jquery.min.js"></script> <meta name="viewport" content="width=device-width, initial-scale=1" /> <link href="sample1_files/bootstrap-3.3.5/css/bootstrap.min.css" rel="stylesheet" /> <script src="sample1_files/bootstrap-3.3.5/js/bootstrap.min.js"></script> <script src="sample1_files/bootstrap-3.3.5/shim/html5shiv.min.js"></script> <script src="sample1_files/bootstrap-3.3.5/shim/respond.min.js"></script> <script src="sample1_files/navigation-1.1/tabsets.js"></script> <link href="sample1_files/highlightjs-9.12.0/default.css" rel="stylesheet" /> <script src="sample1_files/highlightjs-9.12.0/highlight.js"></script> :