LoginSignup
2
5

More than 1 year has passed since last update.

R Markdownで日本語のレポート(別記事にまとめました)

Last updated at Posted at 2021-01-10

変更点が多すぎて新しく記事にしました。
R Markdown(とXeLaTeX)で日本語レポート

この記事について

RMarkdownでレポートや論文を作成するにあたって、初期設定のために色々と試行錯誤したのでまとめておく。完璧なものではない。
ほとんど自分用のメモみたいなもので、まとめた内容よりもどこから情報を収集したのかを記録しておきたい。

いくつかの問題点

natbibを有効にすると:
I couldn't open style file plainnat.bst
どうもうまくいかないのでひとまずあきらめた。

bstも日本語の関係でうまくないので、とりあえずあきらめた。
いわゆるjeconunicodeを有効にすると:
is.kanji.str$ is an unknown function
というエラーが大量に吐き出される。

警告メッセージが出る:
Package microtype Warning: Could not parse font size '10\jsc@mpt '

rmdjaでlualatexをエンジンにしたらうまくいった。
なんで以前はうまくいかなかったのか謎。
ただしこの場合、nociteが効かなくなるので、本文で引用するしかない。

* 目次の見出しとページ数の間が空白になる。「・・・」が欲しいがうまく設定する方法が見つからない。
* 目次の「参考文献」だけが違う体裁になってしまう。明朝体で、ページ数も右寄せにならない。

やっぱりうまくコンパイルしてくれない問題について

  • どうやら、一度rmdjaでコンパイルしてから通常のpdf_documentでもう一度コンパイルするとうまくいくようだ。どういうこと?まぁいいや。たぶんrmdjaが生成する何かしらのファイルがpdf_documentで再利用されてなんかイイ感じになるんだろう。
  • あと参考文献が目次にうまく表示されない問題は、ここを参考にして解決した。
  • 目次の体裁を変更するパッケージtocloftというものがあったので使った。$\mathrm{\LaTeX}$のデフォルトの形を再現できた(と思う)。なぜか普通にheader-includes:styとして読み込んでも反映してくれない。in_header: preamble.texとする(もちろん名前は何でもいい)。この辺の挙動をよく理解していない。

コンパイルの順番を間違えると大変なことになる

  • 例によって理由はわからないが、コンパイルの順番を逆にすると生成されるblgファイルが一気に数ギガバイトに膨れ上がる事象を確認した。順番を間違えるとやばい。

謝辞

ネット上の情報提供者に感謝。この記事もその数多の有益な情報の一滴になれば幸い。
不具合等気兼ねなくフィードバックいただけますよう。

テンプレート

rmdjaテンプレート

yaml
```
title: "タイトル"
author: "氏名"
date: "`r Sys.Date()`"
output:
  rmdja::pdf_book_ja:
    latex_engine: lualatex
    citation_package: natbib
    citation_options: authoryear
    toc: true
    pandoc_args:
      - '--top-level-division=section'
    fig_caption: yes
    number_sections: true
    dev: cairo_pdf
    keep_tex: true
documentclass: ltjsarticle
luatexjapresetoptions: ms
classoption:
  - a4paper,10.5ptj,ja=standard

indent: true
bibliography: myrefs.bib
biblio-style: jeconunicode
pandoc_args: ["-F=pandoc-crossref"]
link-citations: false
header-includes:
  - \usepackage{bxjalipsum}
```
setup
```{setup, include=FALSE}
options(tinytex.latexmk.emulation = F)
rmdja::set_graphics_font(rmdja::get_default_font_family("lualatex")["serif"])

# サンプル引用文献リストを取得する
file.copy("C:/texlive/texmf-local/bibtex/bib/local/myrefs.bib", to = "./")
file.copy("C:/texlive/texmf-local/bibtex/bst/local/jeconunicode.bst", to = "./")
file.copy("C:/texlive/texmf-local/tex/latex/mymacros/mymarkdown.sty", to = "./")

library(knitr)
library(tidyverse)
library(kableExtra)
library(fontregisterer)
library(systemfonts)
family_sans <- "MS Gothic"
family_serif <- "MS Mincho"
theme_set(
  theme_classic() +
  theme(
    text = element_text(family = family_serif, face = "plain"),
    title = element_text(face = "plain"),
    axis.title = element_text(face = "plain"),
    axis.title.x = element_text(face = "plain"),
    axis.title.y = element_text(face = "plain")
  )
)

knitr::opts_chunk$set(
  echo = FALSE, warning = FALSE, message = FALSE,
  out.width = "\\textwidth", fig.align = "center",
  fig.pos = "t")
```

pdf_documentテンプレート

yaml
```
title: '日本国憲法'
author: "\\@MTRBEKTCBT"
date: "`r Sys.Date()`"
output: 
  pdf_document:
    latex_engine: lualatex 
    citation_package: natbib
    dev: cairo_pdf
    fig_caption: yes
    number_sections: true
    toc: true
    keep_tex: true
    pandoc_args:
      - '--top-level-division=section'
    includes:
      in_header: preamble.tex
documentclass: ltjsarticle
luatexjapresetoptions: ms
classoption:
  - a4paper,10.5ptj,ja=standard
link-citations: false
indent: true
pandoc_args: ["-F=pandoc-crossref"]
bibliography: myrefs.bib
biblio-style: jeconunicode
header-includes:
  - \usepackage{bxjalipsum}

figureTitle: " "
tableTitle: " "
listingTitle: "コード "
figPrefix: "図."
eqnPrefix: "式."
tblPrefix: "表."
lstPrefix: "コード."
```

in_headerpreamble.texとして読み込む。ワーキングディレクトリに置く。

preamble.tex
\usepackage{tocloft}
\renewcommand{\cftsecfont}{}
\renewcommand{\cftsecpagefont}{}
\renewcommand{\cftsecleader}{\cftdotfill{\cftdotsep}}
\setlength\cftbeforesecskip{0pt}
setup
```{setup, include=FALSE}
options(tinytex.latexmk.emulation = F)

# サンプル引用文献リストを取得する
file.copy("C:/texlive/texmf-local/bibtex/bib/local/myrefs.bib", to = "./")
file.copy("C:/texlive/texmf-local/bibtex/bst/local/jeconunicode.bst", to = "./")
file.copy("C:/texlive/texmf-local/tex/latex/mymacros/mymarkdown.sty", to = "./")

# データ分析に使う
library(knitr)
library(tidyverse)
library(kableExtra)

# フォント周り
library(fontregisterer)
library(systemfonts)
family_sans <- "MS Gothic"  # "Noto Sans CJK JP"
family_serif <- "MS Mincho"  # "Noto Serif JP"
theme_set(
  theme_classic() +
  theme(
    text = element_text(family = family_serif, face = "plain"),
    title = element_text(face = "plain"),
    axis.title = element_text(face = "plain"),
    axis.title.x = element_text(face = "plain"),
    axis.title.y = element_text(face = "plain")
  )
)

knitr::opts_chunk$set(
  echo = FALSE, warning = FALSE, message = FALSE,
  out.width = "\\textwidth", fig.align = "center",
  fig.pos = "t")
```

出力結果

奥村(2020)に倣い、日本国憲法を書いてみる。あと適当にプロットしてみる。文献は適当。

contents

# 憲法前文

\jalipsum[1-2]{preamble}


# THE CONSTITUTION OF JAPAN

We, the Japanese people, acting through our duly elected representatives in
the National Diet, determined that we shall secure for ourselves and our 
posterity the fruits of peaceful cooperation with all nations and the 
blessings of liberty throughout this land, and resolved that never again shall 
we be visited with the horrors of war through the action of government, do 
proclaim that sovereign power resides with the people and do firmly establish 
this Constitution. Government is a sacred trust of the people, the authority 
for which is derived from the people, the powers of which are exercised by the 
representatives of the people, and the benefits of which are enjoyed by the 
people. This is a universal principle of mankind upon which this Constitution 
is founded. We reject and revoke all constitutions, laws, ordinances, and 
rescripts in conflict herewith.

We, the Japanese people, desire peace for all time and deeply conscious of the
high ideals controlling human relationship, and we have determined to preserve 
our security and existence, trusting in the justice and faith of the peace-
loving peoples of the world. We desire to occupy an honored place in an 
international society striving for the preservation of peace, and the 
banishment of tyranny and slavery, oppression and intolerance for all time 
from the earth. We recognize that all peoples of the world have the right to 
live in the peace, free from fear and want.

```{r mtcars, fig.cap="自動車の排気量と燃費の相関関係", fig.height=3}
mtcars %>% 
  ggplot(aes(disp, mpg, color=factor(cyl))) +
  geom_point()
```

```{r data-mtcars}
mtcars[1:5, 1:6] %>%
  kbl(caption = "mtcarsデータ", booktabs = T) %>% 
  kable_styling(full_width = T) %>% 
  column_spec(1, width = "5cm")
```

[@pocket2020;
@kenpo;
@googlebooks_wagahai;
@夏目1990吾輩;
@Natsume2011cat]

<!-- 参考文献 -->
\newpage
\addcontentsline{toc}{section}{\bibname}

rmarkdown_pdf_template-1.png

rmarkdown_pdf_template-2.png

rmarkdown_pdf_template-3.png

はぁ、やっと思う存分レポートが書ける、か?

参考文献

目次の体裁を変更する方法について
https://tex.stackexchange.com/questions/53126/how-to-change-vertical-spacing-in-toc-between-section-entry-and-only-the-first-s
https://qiita.com/shohirose/items/52f778ebd21f8e5f5c0e
https://texdoc.org/serve/tocloft/0

参考文献を目次にうまく表示する方法について
https://blog.ashija.net/2017/10/24/post-2511/
https://qiita.com/yfur/items/23434dd40d4b4edab102

Markdown、図表、相互参照とか。基本的なことはここ。(Dockerってなに?)
https://qiita.com/Kumassy/items/5b6ae6b99df08fb434d9

グラフの日本語表示について(fontregisterer。rmdjaも使ってみたいが自分の環境ではエラー)
https://ill-identified.hatenablog.com/entry/2020/10/03/200618

cairo_pdfについて
https://stackoverflow.com/questions/55009313/how-to-use-cairo-pngs-in-r-markdown
https://python5.com/q/jydlryhf

相互参照について
https://stackoverflow.com/questions/31926623/figures-captions-and-labels-in-knitr

pandoc-crossrefについて(よくわかってない)
https://stackoverflow.com/questions/41084793/referencing-a-simple-table-in-rmarkdown

pandocオプションについて(luatexjapresetoptions)
https://qiita.com/sky_y/items/15bf7737f4b37da50372

図の大きさについて(紙幅に合わせて横幅を決められると便利)
https://nigimitama.hatenablog.jp/entry/2019/01/13/021447
https://stackoverflow.com/questions/44247571/in-knitr-how-to-set-figure-width-with-textwidth-from-latex
https://ja.ojit.com/so/r/1615559
https://keachmurakami.github.io/2016/08/05/YAMLknitr.html

kableについて(主に桁数の設定について)
https://www.366service.com/jp/qa/06e43e3b75b0c36a4c0b08768485ac8b
https://www.rdocumentation.org/packages/knitr/versions/1.30/topics/kable

bibliographyについて
https://bookdown.org/yihui/rmarkdown-cookbook/bibliography.html
https://rmarkdown.rstudio.com/authoring_bibliographies_and_citations.html

yamlについて
https://qiita.com/Atsushi776/items/9ef1e5d744e2b91c61ee#lualatex%E3%82%92%E7%94%A8%E3%81%84%E3%82%8B%E5%A0%B4%E5%90%88

数式フォントについて
http://ctan.math.washington.edu/tex-archive/fonts/stix2-type1/stix2.pdf
https://qiita.com/kakinaguru_zo/items/95a86668abcf09c7c9c4

jeconunicodeについて
https://qiita.com/shiro_takeda/items/92adf0b20c501548355e
http://shirotakeda.org/ja/tex-ja/jecon-ja.html

書籍
Rではじめるデータサイエンス(Amazon)
https://r4ds.had.co.nz/
Rグラフィックスクックブック(Amazon)

2
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
5