Search code examples
rlatexknitrgt

R gt package: error in latex ("there's no line here to end")


I am trying to include a table generated with the gt() function in a tex file. I create a .Rnw file, then weave it with knitr and compile with pdflatex. During compilation I get an error: "there no line here to end", caused by a newline inserted by gt() in the table header. This is a MWE:

\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage{booktabs}
\usepackage{longtable}
\usepackage{caption}

\begin{document}
<<setup, include=FALSE>>=
library(knitr)
library(tidyverse)
library(gt)
opts_chunk$set(echo=FALSE)
@

This is a dataframe formatted with the \texttt{gt} package.

<<>>=
tibble(
  group=rep(c("A", "B"), each=5),
  age = c(20, 24, 22, 27, 29, 21, 24, 23, 30, 31)) %>%
    gt %>%
      tab_header(title="Some title")
@

\end{document}

The resulting table in the tex file is:

\begin{longtable}{lr}
\caption*{
\large Some title\\ 
\small \\ % This newline causes the error
} \\ 
\toprule
group & age \\ 
\midrule
A & 20 \\ 
A & 24 \\ 
A & 22 \\ 
A & 27 \\ 
A & 29 \\ 
B & 21 \\ 
B & 24 \\ 
B & 23 \\ 
B & 30 \\ 
B & 31 \\ 
\bottomrule
\end{longtable}

(I added the comment manually after weaving)

Because of the newline (\\) in the caption I get: ./mwe.tex:69: LaTeX Error: There's no line here to end. Without that newline, the PDF is created as expected. Is there a way to fix this without having to manually edit the tex file?


Solution

  • I found that it is a bug of gt happening when there is no subtitle is defined. The work around is 1) adding a space as a subtitle, or

    tab_header(title = md("Data listing from **gtcars**"), subtitle = md("&nbsp;"))
    

    2) manually edit the tex file removing \small \\ in the logntable.

    Check the issue at https://github.com/rstudio/gt/issues/197