Search code examples
rkablekableextra

Multiple grouping variables using kableExtra


I've got the following dataset:

tab <- tibble(year = c(2017,2017,2017,2018,2018,2018) 
              mth  = c("Apr", "Apr", "Jun", "Jul", "Jul", "Sep"),
              var1 = 1:6,
              var2 = 10:15)

Is it possible to use kableExtra to generate a table of this data where there are two grouping variables, year and month? This would give:

        var1 var2
2017
    Apr   
          1   10
          2   11
    Jun   
          3   12
2018
    Jul
          4   13
          5   14
    Sep   
          6   15

I've tried:

kable(tab[,3:4]) %>% pack_rows(index = table(year$Month, tab$mth))

It works fine with one grouping variable, but it doesn't work for two grouping variables.


Solution

  • This tutorial has great examples and explains how to do this.

    library(dplyr)
    library(kableExtra)
    
    kable(tab, align = "c", col.names = c("","",names(tab)[3:4])) %>%
      kable_styling(full_width = F) %>%
      column_spec(1, bold = T) %>%
      collapse_rows(columns = 1:2, valign = "top")