首页 > 解决方案 > Rmarkdown 正在针织 PDF 中打印乳胶代码

问题描述

我正在运行一个奇怪的结果。我在 Rmarkdown 的文档中插入了许多表格。这是 YAML:

---
output:
  pdf_document:
    toc: true
    toc_depth: 2
    number_sections: true
header-includes:
 \usepackage{float}
 \floatplacement{figure}{H}
 \floatplacement{table}{H}
---

第一个块:

{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE,
                      fig.pos = "H",
                      fig.width=8,
                      fig.height=7,
                      tab.pos = "H",
                      collapse = TRUE,
                      message = FALSE,
                      warning = FALSE,
                      comment = "#>"
)

knitr::opts_knit$set(root.dir = rprojroot::find_rstudio_root_file())

options(knitr.kable.NA = "-")

表格以这种方式插入:

kable(tableX, caption = "Caption", booktabs = TRUE) %>% 
  row_spec(0, bold=TRUE) %>% 
  kable_styling(bootstrap_options = "condensed") %>% 
  column_spec(1, italic = TRUE)

现在,大多数表格都被正确插入了,但只有一张是用乳胶代码打印的,\begin{table},然后是 \caption{},然后是表格,最后是 \end{table}。怎么可能以这种方式打印一个表格而代码相同?

谢谢

标签: pdflatexr-markdownknitrkable

解决方案


当输出选项设置为pdf_document(可以通过选择选项keep_tex并检查生成的.tex文件来查看乳胶代码)或输出设置为时,R markdown 将生成乳胶代码latex_fragment

knitr::kable输出表格的完整乳胶输出(在 tex 模式下),但使用字面上提供的任何标题。然后 knitr 解释器使用生成的乳胶块。\begin当在and环境语句之间的某个地方\end产生了一些非法的东西(例如其中没有转义的标题%),解释器改为产生转义的乳胶代码。

有效代码

```{r tab1, echo=F}
tableX=data.frame(col1 = "Empty data frame")
kable(tableX, caption = "Caption 20pct", booktabs = TRUE) |> 
  row_spec(0, bold=TRUE) |>
  kable_styling(bootstrap_options = "condensed") %>% 
  column_spec(1, italic = TRUE)
```

按预期生成乳胶代码:

\begin{table}

\caption{\label{tab:tab1}Caption 20pct}
\centering
\begin{tabular}[t]{>{}l}
\toprule
\textbf{col1}\\
\midrule
\em{Empty data frame}\\
\bottomrule
\end{tabular}
\end{table}

但是当 a%添加到标题时,乳胶代码生成中断。代码块

```{r tab1, echo=F}
tableX=data.frame(col1 = "Empty data frame")
kable(tableX, caption = "Caption 20%", booktabs = TRUE) |> 
  row_spec(0, bold=TRUE) |>
  kable_styling(bootstrap_options = "condensed") %>% 
  column_spec(1, italic = TRUE)
```

生产

\textbackslash begin\{table\}

\textbackslash caption\{\label{tab:tab1}Caption 20\%\} \centering

\begin{tabular}[t]{>{}l}
\toprule
\textbf{col1}\\
\midrule
\em{Empty data frame}\\
\bottomrule
\end{tabular}

\textbackslash end\{table\}

它只是在 pdf 中呈现为文字乳胶代码。


推荐阅读