今回もBookdownで文章作成中にエラーに出会したので、忘備録として原因と対処法を記録しておきます。
現象
- Rmarkdownで使っていた以下の表作成コードチャンクをBookdownに移植したところ、PDF出力時にLaTeXコンパイルエラーが発生。
```{r label_name_1, echo=FALSE, warning=FALSE, message=FALSE, results='asis'}
cat("\\renewcommand{\\arraystretch}{0.8} \n")
cat("\\setmainfont{Noto Sans CJK JP} \n")
#Input data
data <- data.frame(col1 = c(letters[1:4]),
col2 = c(1:4))
#Table output
data %>%
kable(
format = "latex",
escape = FALSE,
caption = "\\label{label_name_1}タイトルをここに入れてください.",
booktabs = TRUE,
align = "c",
linesep = ""
) %>%
kable_styling(
latex_options = "hold_position",
position = "left",
full_width = FALSE
) %>%
column_spec(
1:length(data),
width = c("7.5cm","7.5cm"),
latex_valign = "m"
) %>%
footnote(
general_title = "",
general = c(
"フットノート1をここに入力",
"フットノート2をここに入力.")
) %>%
print()
cat("\\setmainfont{Noto Serif} \n")
cat("\\renewcommand{\\arraystretch}{1} \n")
```
- PDF出力時に、以下のようなLaTeXエラーが表示される。
! Missing $ inserted.
<inserted text>
$
l.317 ...e_1)\label{label_name_1}タイトルをここに入れてください.}
Try to find the following text in book_filename.Rmd:
...e_1)\label{label_name_1}タイトルをここに入れてください.}
You may need to add $ $ around a certain inline R expression `r ` in book_filename.Rmd (see the above hint). See https://github.com/rstudio/rmarkdown/issues/385 for more info.
Error: LaTeX failed to compile book_filename.tex. See https://yihui.org/tinytex/r/#debugging for debugging tips. See book_filename.log for more info.
原因と推測
Inline R expression don't work when using scientific notation (pdf_document) · Issue #385 · rstudio/rmarkdown
Using inline R expression don't work when using scientific notation with rmarkdown and template pdf_document. Here I inc...
- ヒントとして表示された、上記GitHubのissueやログファイルを確認しましたが、該当ケースは見当たらず。
- 思い当たる原因としては、キャプション内の\label{...}にアンダースコア(_)を使用していたこと。
解決方法
以下のように、label名からアンダースコアを除去することで、エラーなくPDF出力ができた。
```{r labelname1, echo=FALSE, warning=FALSE, message=FALSE, results='asis'}
cat("\\renewcommand{\\arraystretch}{0.8} \n")
cat("\\setmainfont{Noto Sans CJK JP} \n")
#Input data
data <- data.frame(col1 = c(letters[1:4]),
col2 = c(1:4))
#Table output
data %>%
kable(
format = "latex",
escape = FALSE,
caption = "\\label{labelname1}タイトルをここに入れてください.",
booktabs = TRUE,
align = "c",
linesep = ""
) %>%
kable_styling(
latex_options = "hold_position",
position = "left",
full_width = FALSE
) %>%
column_spec(
1:length(data),
width = c("7.5cm","7.5cm"),
latex_valign = "m"
) %>%
footnote(
general_title = "",
general = c(
"フットノート1をここに入力",
"フットノート2をここに入力.")
) %>%
print()
cat("\\setmainfont{Noto Serif} \n")
cat("\\renewcommand{\\arraystretch}{1} \n")
```
まとめ
- BookdownでのLaTeX出力時には、label名にアンダースコア(_)を使うとコンパイルエラーになる場合がある。
- Rmarkdownで問題がなかったとしても、Bookdownに移植した際には注意する必要がある。