如何在 Rmarkdown 文档中创建乳胶 table?

How to create latex table within an Rmarkdown document?

我想将乳胶 table 插入 .rmd 文件。但是,当我尝试编译 pdf 时收到此错误(我已经能够在背面重现 table)。

---
title: "Test"
author: "me"
date: "1/27/2019"
output: 
  pdf_document: 
    keep_tex: yes
---

## Table

\begin{table}[]
\centering
\begin{tabular}{|l|c|c|}
\hline
      & Sad                                                & Happy                                              \ \hline
Short & \begin{tabular}[c]{@{}l@{}}Sam\ Beth\end{tabular} & \begin{tabular}[c]{@{}l@{}}Jim\ Sara\end{tabular} \ \hline
Tall  & \begin{tabular}[c]{@{}l@{}}Erin\ Ted\end{tabular} & \begin{tabular}[c]{@{}l@{}}Bob\ Ava\end{tabular}  \ \hline
\end{tabular}
\caption{My caption}
\label{my-label}
\end{table}

#ERROR
! Misplaced \noalign.
\hline ->\noalign 
                  {\ifnum 0=`}\fi \hrule \@height \arrayrulewidth \futurelet...
l.105 \textbackslash{} \hline
                              Tall \& 

这是我希望 table 的样子

我不太清楚为什么会出现这个错误。另一种解决方案是将 kable 与包 kableExtra:

结合使用
```{r}
library(knitr)
library(kableExtra)
df <- data.frame(Cat = c("Short", "Tall"), 
                 Sad = linebreak(c("Sam\nBeth", "Erin\nTed")), 
                 Happy = linebreak(c("Jim\nSara", "Bob\nAva")))
kable(df, col.names = c("", "Sad", "Happy"), escape = F, caption = "My caption") %>%
  kable_styling(latex_options = "hold_position")
```

与表格对齐相关的错误有时与缺少的乳胶包有关 dcolumnkableExtra 自动将一堆乳胶包添加到序言中,这可能解释了为什么 kableExtra 解决方案有效。也许尝试在 YAML / 序言中加载 dcolumn 包:

---
title: "Test"
author: "me"
date: "1/27/2019"
output: 
  pdf_document: 
    keep_tex: yes
header-includes:
  \usepackage{dcolumn}
---