Search code examples
rlatexr-markdownkableextra

How to fill entire cell background in column headers in kableExtra when knitting to PDF?


I'm knitting a table to PDF with the kableExtra package in R Markdown, and I'm wondering if anyone has a solution to ensure the background colour of the column headers (black), column group headers (black) and pack rows (red) fills the entire cell. As the image below shows, the respective cells are only filled partially which looks a bit silly.

enter image description here

Example code:

---
title: "Test Doc"
output: pdf_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(
  echo = FALSE,
  message = FALSE,
  warning = FALSE,
  dev = "cairo_pdf"
  )
```

```{r}
library(tidyverse)
library(kableExtra)
```

```{r}
set.seed(1)

df <- data.frame(
  id = LETTERS[1:10],
  var1 = rnorm(10, 50, 10),
  var2 = rnorm(10, 50, 10),
  var3 = rnorm(10, 50, 10),
  var4 = rnorm(10, 50, 10),
  var5 = rnorm(10, 50, 10),
  var6 = rnorm(10, 50, 10),
  grp = rep(paste("Group", 1:2), each = 5)
)
```

```{r}
kbl(df[1:7],
    booktabs = TRUE,
    escape = FALSE,
    align = c("l", rep("c", ncol(df) - 1))) %>%
  kable_styling(latex_options = c("HOLD_position"),
                font_size = 8) %>%
  add_header_above(c(" " = 1, "colgroup1" = 3, "colgroup2" = 3), background = "black",
                     color = "white", bold = TRUE) %>%
  row_spec(row = 0, background = "black", color = "white", bold = TRUE) %>%
  pack_rows(index = table(fct_inorder(df$grp)), background = "#ED1B2F",
            color = "white", bold = TRUE, extra_latex_after = "\\midrule{}")
```

Solution

  • This approach removes the spacing between rows to remove the white spaces.

    Try:
    a) removing the booktabs argument, which forces extra line spaces every 5 rows.
    b) add linesep = "" so there is no line separation, and then
    c) in the call to pack_rows remove the space after the grouping row extra_latex_after = "".

    ```{r}
    
    kbl(df[1:7],
        # booktabs = TRUE,
        escape = FALSE,
        align = c("l", rep("c", ncol(df) - 1)),
        linesep = "")  |> 
      kable_styling(latex_options = c("HOLD_position"),
                    font_size = 8)  |> 
      add_header_above(c(" " = 1, "colgroup1" = 3, "colgroup2" = 3), 
                       background = "black",
                       color = "white", 
                       bold = TRUE)  |> 
      row_spec(row = 0, 
               background = "black", 
               color = "white", 
               bold = TRUE) |> 
      pack_rows(index = table(fct_inorder(df$grp)), background = "#ED1B2F",
                color = "white", 
                bold = TRUE,
                extra_latex_after = "")
    ```
    

    Results in:

    enter image description here