Search code examples
rlatexr-markdownkable

How to remove unnecessary white space between title and table using kable in R Markdown to Beamer


I want that the title of my table (blabla) goes close to the top of the table (no extra space). This question may be the same as from Sara, but I provide a reproducible example. I have tried these tips, but they don't work out.

---
title: "XYZ"
output: 
  beamer_presentation
---
```{r, include=FALSE}
library(knitr)
```
## 
```{r}
kable(mtcars[1:2,1:2],
      caption = "blabla",
      format = "latex")
```

\begin{table}

\caption{blabla}
\centering
\begin{tabular}{l|r|r}
\hline
  & mpg & cyl\\
\hline
Mazda RX4 & 21 & 6\\
\hline
Mazda RX4 Wag & 21 & 6\\
\hline
\end{tabular}
\end{table}

Produces:

enter image description here

How can I remove the extra white space (in either case)? It would better a proper solution, i.e., without manually changing the LaTeX code from kable...


Solution

  • Half of the white space is caused by rmarkdown using \begin{tabular}[t]{l|r|r} instead of \begin{tabular}{l|r|r}

    The other half is the default spacing beamer uses below captions. You can control it via \setlength\belowcaptionskip{7pt}, but I would suggest to keep changes restricted to the table environment to not effect places where the caption is supposed to be below stuff like figures.

    \documentclass{beamer}
    
    \AtBeginEnvironment{table}{\setlength\belowcaptionskip{0pt}}
    
    \begin{document}
        
    \begin{frame}
    \begin{table}
    \caption{content...}
    \begin{tabular}{cc}
    \hline
    c & d\\
    \hline
    \end{tabular}
    \end{table}
    \end{frame} 
    
    \begin{frame}
    \begin{figure}
    \includegraphics[width=.5\textwidth]{example-image-duck}
    \caption{content...}
    \end{figure}
    text
    \end{frame} 
        
    \end{document}