R
RStudio
!!!R Markdown
{{outline}}
----
!!基本
*メニューのファイルの下、左端の+マークから、R Markdownを選ぶ
*メニューのFileからNew File で選ぶ
**Text File を選んでおいて、ファイル保存時に、拡張子 .rmd を付けて保存する。
!MarkdownのHelp
*メニューのHelpから Markdown Quick Reference を選ぶ
!見出し
{{pre
# Header 1
## Header 2
### Header 3
#### Header 4
}}
!改行は、空行を一行入れる。
* 強制改行は、行末にスペース二つ
* 見た目二行でも、空行が入ってないと、結果、つながって表記される。
!書体
{{pre
*italic* **bold**
_italic_ __bold__
^上付き文字^
~下付き文字~
~~打消し~~
下線
}}
!文字の色
*HTMLで指定する
このデータを使用
!特殊文字
* RMarkdownの中で使われる特殊文字のエスケープはバックスラッシュ一つ
\*
\#
!箇条書き
* 行頭に * か数字.
* 数字は何が書いてあっても、自動的に1からふってくれる
** 全部 1. にしておいた方が無難(見た目と結果がずれてしまう)
{{pre
* 項目
* 項目
1. 番号付き
2. 番号付き
3. 番号付き
}}
*階層は、<<前に四つスペース>>
{{pre
* 項目
* 下位項目
* 下位項目
}}
!横線(トラブルのもとなので使わないほうが良い)
---
!そのまま
```
そのままの文
そのままの文
```
!数式
{{pre
$$
y = a * x^b
freq = 7592 * rank^{-0.6}
$$
}}
!引用
> 引用文
> 引用文
!表
*縦棒で区切る
*一番上が見出し
*二行目が配置の設定(コロンの位置)
**コロンが左 左寄せ
**コロンが右 右寄せ
**コロンが左右 中央(|:---:|)
{{pre
|指標|説明|
|:----|:---|
| i| ファイル名|
| Score| Criterionスコア|
| Tokens| 総語数|
| Types| 異なり語数|
| NoS| 文数|
| TTR| 語彙多様性|
| GI| 語彙多様性|
| MATTR| 語彙多様性|
| AWL| 平均単語長(文字数)|
| ASL| 平均文長(単語数)|
}}
!!ヘッダー部分の設定
*https://qiita.com/kazutan/items/726e03dfcef1615ae999
*https://bookdown.org/yihui/rmarkdown/html-document.html
!タイトル
title:
subtitle:
abstract:
!テーマ
theme:
** theme一覧
https://bootswatch.com/3/
!TOC 目次オプション toc: true
* toc_depth: 数字 で深さ設定
* toc_float: true で固定ではなくて浮くように
* number_sections: true で番号付きに
! 日付と時間
date:
* 自動で入れる
date: "`r Sys.time()`"
** ただし、これでは、明示的に、いつかいた文書かがわからなくなる。
** Knitした時点での日付と時間になる
!使用例
{{pre
title: "タイトルを書く"
subtitle: "副題"
abstract: "概要を簡単にまとめて書いておく"
author: "sugiura"
date: "2023-02-09"
output:
html_document:
toc: true
toc_float: true
theme: cerulean
number_sections: true
---
}}
!!chunkコード
!文書全体にわたるオプションのデフォルトの設定は、最初に
knitr::opts_chunk$set()
で、設定しておく。
*RMarkdownのファイルを作るとデフォルトで
knitr::opts_chunk$set(echo = TRUE)
となっている。
** なので、最初に表示されるサンプルの最初の部分を修正して使えばよい。
** echo=TRUEは、デフォルトで、そうなので、逆に言えば、削除しても事実上問題ない。
* 便利な例:グラフの幅を統一して設定したい場合、
knitr::opts_chunk$set(echo = TRUE, fig.width=10, fig.height=7)
** デフォルトでは、widthは7、heightは5
!Rのコード
{{pre
```{r}
ここに書く
ここに書く
ここに書く
```
}}
!コードのオプション
*```{r sample} のように名前を付けておくこともできる
*```{r, include=FALSE} コードは実行されるが、コードも結果も表示されない
*```{r, echo=FALSE} コードを表示せず、実行結果だけ出力
*```{r, eval=F} コードは表示されるが実行されない
*```{r, results='hide'} コードは実行されるがKnitのレポートには表示されない
!警告を出さない
warning=F
!メッセージを出さない
message=F
!プロットの結果出力のオプション
*fig.height = 7
*fig.width = 7
*fig.align = "left"
*fig.cap = "キャプション"
*dpi = 72
!インラインコード
**文中に `r コードを描く` としておけば、コードの実行結果がそこに出力される。
!!その他
!画像の挿入
*Rmdソースコードと同じフォルダーに入れておくのが簡単


* 画像のサイズの調整 {width=80%}
!コメント
{{pre
}}
* 命令を書く部分(code chunk)では、該当行を選んでおいて、Ctrl+Shift+C
!データフレームの見やすい表示 kable()
* コードチャンク内で、データフレームを指定する
kable(データフレーム)
* もしくは、ヘッダー部分で以下のように記述すれば全体がそうなる
{{pre
output:
html_document:
df_print: "kable"
}}
* "paged" という形式もある
!!書き終わったら、上の Knit をクリックすると、レポートが作成される。
*HTMLでの書き出しでのオプション
**toc: true で目次作成
**toc_float: true で左に目次表示
**number_sections: true で見出しに通し番号付与
{{pre
output:
html_document:
toc: true
toc_float: true
number_sections: true
}}
{{pre
author: "sugiura"
date: "2022/11/11"
output:
html_document:
toc: yes
number_section: yes
word_document:
toc: yes
pdf_document:
toc: yes
}}
*html_document<<:>> のところ、コロン忘れずに
!グラフのサイズの調整:fig.width=インチ, fig.height=インチ
```{r, fig.width=15, fig.height=10}
* これで縦横比を調整すればよい
```{r, fig.width = 10, fig.height = 4}
!knitディレクトリーに注意
*RMarkdownで記述しながら、Chunkを実行していく際に、スクリプトやコンソールで設定している作業ディレクトリーとは別に、Knit Directory で設定するディレクトリーが別にあるので注意。
**Document Directory
**Project Directory
**<>
*スクリプト内で setwd()で作業ディレクトリーを変更しても、チャンク内の一連の処理が終わったら、また、元のディレクトリーに戻ってしまう。
*Knit Directoryが変更されない限り、ドキュメント内での作業ディレクトリーは、チャンク内のsetwd()でセットしたディレクトリーではなくKnit Directoryで設定されているディレクトリーのままになっている。Knitのメニューから手動で変更する必要がある。
!!BibTeX 文献の引用と文献リストの作成
* なんと、LaTeXのように使える。
!準備
*参考文献をBibTeX形式のテキストファイル(例 LCR.bib)で用意し、RStudioで読み込んでおく。
** 文字コードはUTF-8にしておく。SHIFT-JISだとエラー。
{{pre
@article{lijffijt2012correction,
title={Correction to Stefan Th. Gries’“Dispersions and adjusted frequencies in corpora”, International Journal of Corpus Linguistics},
author={Lijffijt, Jefrey and Gries, Stefan Th},
journal={International Journal of Corpus Linguistics},
volume={17},
number={1},
pages={147--149},
year={2012},
publisher={John Benjamins}
}
@article{gries2008dispersions,
title={Dispersions and adjusted frequencies in corpora},
author={Gries, Stefan Th},
journal={International journal of corpus linguistics},
volume={13},
number={4},
pages={403--437},
year={2008},
publisher={John Benjamins}
}
@incollection{gries2010dispersions,
title={Dispersions and adjusted frequencies in corpora: further explorations},
author={Gries, Stefan Th},
booktitle={Corpus-linguistic applications},
pages={197--212},
year={2010},
publisher={Brill}
}
}}
*Rmarkdownのヘッダー部分で、bibliography: LCR.bib のように、使用するファイルを指定する。
{{pre
output:
html_document:
toc: yes
number_section: yes
word_document:
toc: yes
pdf_document:
toc: yes
bibliography: LCR.bib
}}
!執筆
*RMarkdown文書中で、引用個所をLaTeXのように、記述する。
** @の後ろに各文献の引用コードを書く。
{{pre
@lijffijt2012correction は、@gries2008dispersions の訂正記事です。
@gries2010dispersions にもまとめが書いてあります。
}}
!出力
* ただ普通に、Knitするだけ。
* 本文中に著者名と年号が挿入され、
----
{{ref_image bibhonbun.png}}
----
*文書の最後に、参考文献一覧が整形されて付け足される。
*文書の最後に「 # References」と書いておけば、その下に、文献一覧が並ぶ。
----
{{ref_image bibreferences.png}}
----
!!論文の原稿を作る際のコツ
* セクションの見出しは #
* サブセクションは、##
* コードチャンクに、それが何をするものか説明を書いておく
```{r エクセルファイルからデータ読み込み}
*数式はTeX形式で表記可能
*図の出力は、plot()でなく、チャンクオプションで、デバイスで画像出力
```{r, dev="png"}
** 二種類ほしかったら
```{r, dev=c("png", "jpg")}
https://www.njtierney.com/post/2018/02/28/three-r-tips/
**最初から、全部
knitr::set_opts(dev = "jpg")
!Writing Reproducible Research Papers with R Markdown <<すばらしい>>
https://resulumit.com/teaching/rmd_workshop.html
!!スライド作成
!R Markdownでスライドを作成(ioslides)
https://qiita.com/masato-terai/items/664c5ee782f690260eca
by @masato-terai(テライ マサト)
!!テンプレート
!よく使うパタン(以下をRmdファイルにコピペ)
{{pre
---
title: "ReadingSpeed"
author: "sugiura"
date: "2025-07-29"
output:
html_document:
toc: yes
number_section: yes
word_document:
toc: yes
---
# 準備
## 使用するライブラリ
```{r, warning=F, message=F}
library(tidyverse)
library(lme4)
library(lmerTest)
library(effects)
library(ggplot2)
library(jtools) # APAフォーマットのテーマ theme_apa()
library(openxlsx)
```
## Dataの所在
* PC内でエクセルでまとめたファイルがどこにあるか、パスをコピーして記録しておく
* 例
* "C:\Users\sugiura\ed\2025\ReadingSpeed\ReadingSpeed.xlsx"
# データ読み込み
```{r}
sample.dat <- read.xlsx("ReadingSpeed.xlsx", sheet="data")
str(sample.dat)
```
## 型の設定
```{r}
sample.dat$ID <- as.factor(sample.dat$ID)
sample.dat$Item <- as.factor(sample.dat$Item)
sample.dat$Time <- factor(sample.dat$Time, levels=c("Pre", "Post"))
str(sample.dat)
```
# 分布の確認
```{r}
g <- ggplot(sample.dat)
g <- g + aes(x=Time, y=Score, fill=Item)
#g <- g + geom_point()
g <- g + geom_boxplot()
#g <- g + geom_smooth()
#g <- g + geom_line()
#g <- g + geom_density(alpha=.7)
g <- g + facet_wrap(~Item, scales="free")
plot(g)
```
# 分析 GLMM
```{r}
#sample.model <- glmer(Score ~ Time * Item + (1|ID), family=gaussian, data=sample.dat)
sample.model <- glm(Score ~ Time * Item , family=gaussian, data=sample.dat)
summary(sample.model)
```
```{r}
plot(allEffects(sample.model), multiline=T, confint = list(style = "auto"))
```
}}
!!References
*https://gihyo.jp/admin/serial/01/r-markdown/0002
*https://gihyo.jp/admin/serial/01/r-markdown/0003
https://epirhandbook.com/jp/rmarkdown.html
*https://mom-neuroscience.com/r-rmarkdown/
*https://blog.atusy.net/2021/01/21/rmd-bs4/
**スタイルの変更
*宋財泫 (Jaehyun Song)・矢内勇生 (Yuki Yanai)「私たちのR: ベストプラクティスの探究」https://www.jaysong.net/RBook/
*R Markdown: The Definitive Guide
https://bookdown.org/yihui/rmarkdown/
* R Markdown from RStudio
https://rmarkdown.rstudio.com/lesson-1.html
https://kazutan.github.io/kazutanR/Rmd_intro.html#r_markdown%E3%81%AE%E6%9B%B8%E3%81%8D%E6%96%B9
https://www.docswell.com/s/3818391906/521P6K-2022-04-16-132212#p1
https://youtu.be/dbljY7jxrSA