Search code examples
rgroupingkableextra

How to group rows in kableExtra with a grouping variable: `pack_rows()`?


library(kableExtra)
library(tibble)

MWE dataset (group = grouping variable)

tib <- tibble(group = c("a", "a", "b", "c", "c", "c"),
              var = 1:6)

This is what I want to achieve:

kable(tib[, 2]) %>% 
  pack_rows(index = c("a" = 2, "b" = 1, "c" = 3))

But with 30 or more unique grouping identifiers this is tedious to do manually. So I have been experimenting with a programmatic approach

I tried using run length encoding but could not get it to work; for example, this code fails:

kable(tib[, 2]) %>% 
  pack_rows(rle(tib$group)[2], rle(tib$group)[1])

I'd be grateful for any pointers or suggestions to resolve this.


Solution

  • You can use a simple table:

    kable(tib[, 2]) %>% 
      pack_rows(index = table(tib$group))
    

    enter image description here

    If your index row is not alphabetical ordered you can do the following with fct_inorder from forcats (contained in tidyverse)

    tib2 <- tibble(group = c("b", "c", "c", "c", "a", "a"),
                  var = 1:6)
    
    kable(tib2[, 2]) %>% 
      pack_rows(index = table(fct_inorder(tib2$group)))
    

    enter image description here