TDP
TDP

Reputation: 374

How to create latex table within an Rmarkdown document?

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 likeenter image description here

Upvotes: 3

Views: 20499

Answers (2)

Omar Wasow
Omar Wasow

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

Martin Schmelzer
Martin Schmelzer

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")
```

enter image description here

Upvotes: 4

Related Questions