#author("2019-06-09T12:58:51+00:00","","")
#mynavi(R言語の練習)
#setlinebreak(on);

* 目次 [#v98206d1]
#contents
- 関連
-- [[R言語入門]]
-- [[Rでグラフ描画]]

* 概要 [#z21a9a8c]
#html(<div style="padding-left: 10px;">)
Rの集計、分析結果を Markdown形式で作成するための R Markdown というパッケージが提供されている。
レポートの形式は HTML の他に Word や PDF 等も対応しているが、当記事では HTML の生成についてのみ記載する。
#html(</div>)

* インストール [#e9922c4c]
#html(<div style="padding-left: 10px;">)

とりあえず rmarkdown と knitr をインストール。
尚、word文書等を作成する場合は pandoc も必要だが、当記事では扱わない為、インストールしない。

#myterm2(){{
install.packages("rmarkdown")
install.packages("knitr")
install.packages("reticulate")    # コードチャンクを python などの他言語で書く場合は必要
}}
#html(</div>)

* 基本的な使い方 [#m7de42bf]
#html(<div style="padding-left: 10px;">)

Markdown 形式のファイルを拡張子 Rmd で作成し、render するだけ。
※Rmd の記述方法等は後述。

** .Rmd の作成 [#j36c88bb]
#html(<div style="padding-left: 10px;">)

sample.Rmd
#mycode2(){{
---
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)
```

}}

#html(</div>)

** rmarkdown::render の実行 [#va9ef8ac]
#html(<div style="padding-left: 10px;">)
#myterm2(){{
library(rmarkdown)
render("sample.Rmd")
}}
#html(</div>)

これだけで sample.html が出力される。

#html(</div>)

* .Rmd の記述方法 [#o47815e8]
#html(<div style="padding-left: 10px;">)


** 基本設定 [#v81fdb6f]
#html(<div style="padding-left: 10px;">)

Rmd の先頭で --- から --- の間に基本的な設定を YAML形式で記述する。

参考
https://rmarkdown.rstudio.com/lesson-9.html
https://bookdown.org/yihui/rmarkdown/html-document.html

#mycode2(){{
---
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
---
}}

#html(</div>)


** コードチャンク [#fb6f9ba9]
#html(<div style="padding-left: 10px;">)

コードチャンクにオプションを設定する事で、挙動の微調整ができる。

参考
https://rmarkdown.rstudio.com/lesson-3.html
https://yihui.name/knitr/options/

基本的なオプション
| オプション | 説明 |h
| include | コードの実行結果を出力内容に含めたくない場合は FALSE を指定する |
| echo | コード自体を出力内容に含めたくない場合は FALSE を指定する |
| message | コード実行時の message による出力を出力内容に含めたくない場合は FALSE を指定する |
| warning | コード実行時の warning による出力を出力内容に含めたくない場合は FALSE を指定する |
| fig.cap | グラフに付けたいキャプションを指定する(alt属性 及び pタグとして出力される) |

使用例)
#mycode2(){{

## 実行時のコードは出力しない
```{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()
```
}}

#html(</div>)


** インラインコード [#ycde5ff3]
#html(<div style="padding-left: 10px;">)

前後をバックスラッシュで囲む事によってインラインコードを記述可能。

参考
https://rmarkdown.rstudio.com/lesson-4.html

#mycode2(){{
### 日付を出力
`r Sys.time()`
}}

尚、基本設定の YAML 部分に書く場合は シングルクォートで括る必要がある。
#mycode2(){{
---
  :
date: '`r Sys.time()`'
  :
---
}}

#html(</div>)


** パラメータ化 [#ia7ad294]
#html(<div style="padding-left: 10px;">)

Rmd 側で使用する値をパラメータ化しておいて、render 時に呼び出し側から渡す事が出来る。
参考: https://rmarkdown.rstudio.com/lesson-6.html

#TODO
参考
https://rmarkdown.rstudio.com/lesson-6.html

#mycode2(){{
---
title: "Sample1"
params:
  param1: "blank"
output: html_document
---

```{r echo = F}
print(params$param1)
```
}}

呼び出し側
#myterm2(){{
library(rmarkdown)
render("sample1.Rmd", params = list(param1 = "test12345"))
}}

実行結果
#html(<div style="padding:5px; border-radius: 5px; border: 1px solid #ccc; margin-top: 5px;">)
## [1] "test12345"
#html(</div>)


#html(</div>)


** 表の描画 [#u0851c58]
#html(<div style="padding-left: 10px;">)

knitr::kable を使用すると データフレームの内容を HTML 等の表(table)として描画する事ができる。
参考
https://rmarkdown.rstudio.com/lesson-7.html

#mycode2(){{
```{r echo = F}
kable(head(iris, 10))
```
}}

#html(</div>)

** タブの描画 [#v283b545]
#html(<div style="padding-left: 10px;">)

出力が縦長になりすぎる場合などは、タブ化できる。

参考
https://bookdown.org/yihui/rmarkdown/html-document.html#tabbed-sections

#mycode2(){{
### タブの描画 {.tabset}

#### By Product
#### Tab1

```{r echo = F}
plot(iris$Sepal.Length, iris$Sepal.Width)
```

#### By Region
#### Tab2

```{r echo = F}
plot(iris$Petal.Length, iris$Petal.Width)
```
}}

#html(</div>)

** 基本的な Markdown記述 [#w25ea964]
#html(<div style="padding-left: 10px;">)

基本的な Markdown 記法はそこそこサポートしてる模様。

参考
https://rmarkdown.rstudio.com/lesson-8.html

#mycode2(){{
### Markdown記法

- リスト1
    - **AAA**
    - **BBB**
- リスト2
    - **CCC**
    - **DDD**

1. リスト1
    - *AAA*
    - *BBB*
1. リスト2
    - *CCC*
    - *DDD*

| col1 | col2 |
|:-----|:-----|
| val1 | val2 |
| val3 | val4 |

}}

#html(</div>)

** R以外の言語で書く場合 [#w8c393bf]
#html(<div style="padding-left: 10px;">)

python など他の言語でコードチャンクを書くための仕組みが提供されている。
※reticulate が必要。

参考
https://rmarkdown.rstudio.com/lesson-5.html
https://bookdown.org/yihui/rmarkdown/language-engines.html

sample.Rmd
#mycode2(){{
```{r include = F, message = F, warning = F}
library(knitr)
library(reticulate)
```

```{python}
x = [i for i in range(10)]
print(x)
```

}}

使用する python のパスを明示したい場合は、呼び出し側で use_python で設定するか、
コードチャンク側で   {python, engine.path = '/usr/bin/python3'} のように指定する事も可能。
使用する python のパスを明示したい場合は、呼び出し側で use_python 、use_virtualenv、use_condaenv 等で設定するか、
コードチャンク側で   {python, engine.path = '/usr/bin/python3'} のように指定する事が可能。

例) 呼び出し側で指定する場合
#mycode2(){{
library(rmarkdown)
library(knitr)
library(reticulate)
use_python("/usr/bin/python3")
render("sample1.Rmd")
}}

例) コードチャンク側で指定する場合
#mycode2(){{
```{python, engine.path = '/usr/bin/python3'}
x = [i for i in range(10)]
print(x)
```
}}

#html(</div>)

** 画像などを base64 エンコードして埋め込みたくない場合 [#l53b403c]
#html(<div style="padding-left:10px;">)

#html(</div>)
基本的に全てのデータは html に内包する形で出力される。

* サンプル [#u8449375]
#html(<div style="padding-left: 10px;">)
例えば、以下の様にグラフをファイルに出力した後に、img タグを描画した場合でも、
img タグは <img src="plot1.png" /> の様には展開されず、base64 エンコードしたデータが埋め込まれた状態で出力される。

sample1.R
sample1.Rmd
#mycode2(){{
library(rmarkdown)
render("rmarkdown/sample1.Rmd")
### ファイル出力後に img タグを描画
```{r echo = F, include = F}
png("plot1.png")
plot(iris$Sepal.Length, iris$Sepal.Width)
dev.off()
```
<!-- imgタグを出力 -->
![](plot1.png)
}}

sample1.Rmd
出力結果
#mycode2(){{
#TODO
<div id="-img-" class="section level3">
<h3>ファイル出力後に img タグを描画</h3>
<!-- imgタグを出力 -->
<div class="figure">
<img src="data:image/png;base64,iVBORw0KGg ..." >
</div>
</div>
}}

header.html
これは script タグや css でも同様で、以下の様に記述した場合
#mycode2(){{
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
}}

doc_suffix.html
それぞれのファイルの内容が css は urlエンコード、js は base64エンコードされてHTMLに埋め込まれる形となる。

生成結果
#mycode2(){{
<script src="script.js"></script>
<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>
}}

style.css

埋め込まずに出力したい場合は、self_contained = false を指定する。

#mycode2(){{
#TODO
---
title: "Sample1"
author: "Daisuke.M"
date: '`r Sys.time()`'
output:
  html_document:
    self_contained: false
---

<link rel="stylesheet" href="style1.css">
<script src="script1.js"></script>

}}

script.js
生成結果
#mycode2(){{
#TODO
<link rel="stylesheet" href="style1.css">
<script src="script1.js"></script>
}}


実行
#myterm2(){{
source("sample1.R")
}}
#html(</div>)

実行結果
** 自動的に組み込まれる js 等について [#za46eb17]
#html(<div style="padding-left:10px;">)
#TODO
#html(</div>)

上記の通り self_contained: false にして出力した結果を見ると、
デフォルトで jquery 等が利用できる状態で出力されている事が分かる。
なので、これらを使用してある程度リッチなコンテンツを作成する事が出来る。(自分で組み込んでも良いが)
※ご丁寧に bootstrap や viewport まで出力されているので、レスポンシブなコンテンツも楽に作成できそう。

#mycode2(){{

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

#html(</div>)

* 注意点 [#ce3ce288]
#html(<div style="padding-left:10px;">)
#TODO
#html(</div>)


トップ   一覧 単語検索 最終更新   ヘルプ   最終更新のRSS