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

时间:2019-01-28 00:49:13

标签: latex r-markdown knitr

我希望将乳胶表插入.rmd文件。但是,当我尝试编译pdf时,我收到此错误(我已经能够在背面打印表格)。

---
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 \& 

这就是我想要的表格enter image description here

2 个答案:

答案 0 :(得分:1)

我不太确定为什么会发生此错误。另一个解决方案是将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")
```

enter image description here

答案 1 :(得分:0)

与表对齐有关的错误有时与缺少的乳胶包装(如dcolumn)有关。 kableExtra会自动在前言中添加一堆乳胶包,这也许可以解释为什么kableExtra解决方案有效。也许尝试在YAML /前言中加载dcolumn包:

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