Search code examples
rkableextra

R kableExtra adds additional empty row when inserting horizontal line


I am creating a Latex table using the kableExtra package in R. I want to insert a horizontal line after a certain row, however, this also automatically adds an empty row. How can this behavior be suppressed?

The problem is coming from the fact that right now it adds \midrule\\ instead of just \midrule.

example

library(kableExtra)

set.seed(123)
df <- data.frame(matrix(runif(9), 3, 3))

kable(
  df,
  booktabs = TRUE,
  format = "latex") %>%
  row_spec(2, hline_after = T)

The corresponding Latex code looks as follows:

\documentclass[letterpaper]{article}
\usepackage{booktabs}

\begin{document}
\begin{tabular}{rrr}
    \toprule
    X1 & X2 & X3\\
    \midrule
    0.2875775 & 0.8830174 & 0.5281055\\
    0.7883051 & 0.9404673 & 0.8924190\\
    \midrule\\
    0.4089769 & 0.0455565 & 0.5514350\\
    \bottomrule
\end{tabular}
\end{document}

A potential workaround seems to be using gsub() and replacing the \midrule\\ component. However, this seems odd and I would think that there is an easier approach. The R code for this looks as follows:

kable(
  df,
  booktabs = TRUE,
  format = "latex") %>%
  row_spec(2, hline_after = T) %>%
  gsub("\\midrule\\\\", "\\midrule", .) %>%
  gsub("\\midrule\\\\", "\\midrule", .)

Solution

  • The empty row after \\midrule is hard coded on kableExtra::spec_row, but looking at the code I think we can use extra_latex_after = "%" to make a comment of the line break.

    See if it works for you:

    kable(
      df,
      booktabs = TRUE,
      format = "latex") %>%
      row_spec(2, hline_after = TRUE, extra_latex_after = "%")
    

    The output:

    \begin{tabular}{rrr}
    \toprule
    X1 & X2 & X3\\
    \midrule
    0.2875775 & 0.8830174 & 0.5281055\\
    0.7883051 & 0.9404673 & 0.8924190\\
    \midrule
    %\\ # <--- HERE!
    0.4089769 & 0.0455565 & 0.5514350\\
    \bottomrule
    \end{tabular}
    

    The table rendered on overleaf: enter image description here

    That's it!


    1 The kableExtra::row_spec code:

    # if (!is.null(background)) {
      #   new_row <- paste0("\\\\rowcolor", latex_color(background), "  ", new_row)
      # }
    
      if (!hline_after & is.null(extra_latex_after)) {
        return(new_row)
      } else {
        latex_after <- "\\\\\\\\"
        if (hline_after) {
          if (table_info$booktabs) {
            latex_after <- paste0(latex_after, "\n\\\\midrule")
          } else {
            latex_after <- paste0(latex_after, "\n\\\\hline")
          }
        }
        if (!is.null(extra_latex_after)) {
          latex_after <- paste0(latex_after, "\n",
                                regex_escape(extra_latex_after, # The `%` goes here
                                             double_backslash = TRUE))
        }
        return(c(new_row, latex_after)) # <--- Always a `latex_after`
      }
    }