Search code examples
rknitrr-markdownkablekableextra

KableExtra - collapse_rows alignment


I put the following code in my R Markdown document and it nicely collapses rows based on the structure of my data frame. As you can see there is an align argument that horizontally aligns the data. Is there a similar align_vertical argument that allows me to align vertically? In particular I'd like the "a" and "b" from the output below to be vertically top-aligned. Currently they are vertically center-aligned.

library(kableExtra)
library(knitr)

collapse_rows_dt <- data.frame(C1 = c(rep("a", 10), rep("b", 5)),
                 C2 = c(rep("c", 7), rep("d", 3), rep("c", 2), rep("d", 3)),
                 C3 = 1:15,
                 C4 = sample(c(0,1), 15, replace = TRUE))

kable(collapse_rows_dt, "html", align = "c") %>%
  kable_styling(full_width = F) %>%
  column_spec(1, bold = T) %>%
  collapse_rows(columns = 1:2)

Solution

  • If you change the order of the commands (execute column_spec at last) you can useextra_cssto change thevertical-align` property:

    library(kableExtra)
    library(knitr)
    
    collapse_rows_dt <- data.frame(C1 = c(rep("a", 10), rep("b", 5)),
                                   C2 = c(rep("c", 7), rep("d", 3), rep("c", 2), rep("d", 3)),
                                   C3 = 1:15,
                                   C4 = sample(c(0,1), 15, replace = TRUE))
    
    kable(collapse_rows_dt, "html", align = "c") %>%
      kable_styling(full_width = F) %>%
      collapse_rows(columns = 1:2) %>%
      column_spec(1, bold = T, extra_css = 'vertical-align: top !important;')
    

    enter image description here