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

2

5
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.

Coconut answered 26/3, 2019 at 9:16 Comment(2)
Maybe collapse_rows is an alternative for you?Disepalous
Thank you!! This solved it for me. Perfect.Cromorne
D
30

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

Disepalous answered 26/3, 2019 at 9:28 Comment(3)
This method only works when the grouping variables are in alphabetical or numerical order, for example if tib$group <- c("c", "c", "c", "b", "a", "a") and tib$var is as before the "table" index method would not result in the correct grouping.Coconut
Then you can first use fct_inorder and then apply the table, see my edit.Disepalous
@Disepalous is there a way to do this with multiple columns?Miele
I
2

group_rows() is accepting a named vector. Here is one way:

kable(tib[, 2]) %>% 
  group_rows(index = setNames(rle(tib$group)[[1]], rle(tib$group)[[2]]))
Isocrates answered 26/3, 2019 at 9:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.