Reputation: 374
I am looking to insert a latex table into an .rmd file. However, when I try to compile the pdf I receive this error (I have been able to reproduce the table in overleaf).
---
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 \&
Here is what I would like the table to look like
Upvotes: 3
Views: 20499
Reputation: 2040
Errors related to alignment in tables are sometimes related to a missing latex package liked dcolumn
. kableExtra
automatically adds a bunch of latex packages to the preamble and that might explain why the kableExtra
solution works. Maybe try loading the dcolumn
package in the YAML / preamble:
---
title: "Test"
author: "me"
date: "1/27/2019"
output:
pdf_document:
keep_tex: yes
header-includes:
\usepackage{dcolumn}
---
Upvotes: 2
Reputation: 23919
I am not quite sure about why this error occurs. Another solution is to use kable
in combination with the package 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")
```
Upvotes: 4