Julius
Julius

Reputation: 21

Use a list to feed the group_rows in kable

I am trying to generate a big table using kable on R. I would like to group some rows using names stored in an object but can't find how to do this.

This is what I have:

kable(Baseline, "html") %>%
  kable_styling("striped") %>%
  add_header_above(c(" " = 1, "My score" = 4)) %>%
  group_rows(index= c(" "=3, "Age" = 4, "BMI" = 4))

In this example I only have 3 categories to subclassify the rows but in reality I have more so wanted to know if it was possible to call an object containing names and number of rows to include instead of writing each factor like:

kable(Baseline, "html") %>%
  kable_styling("striped") %>%
  add_header_above(c(" " = 1, "My score" = 4)) %>%
  group_rows(index= nametable)

Where nametable contains names and number of rows corresponding to this name.

Hope this is clear...

Thank you

Upvotes: 2

Views: 1210

Answers (2)

Earl F Glynn
Earl F Glynn

Reputation: 375

A bit shorter ...

library(tidyverse)
library(kableExtra)

counts <- table(iris$Species)

iris %>%
  arrange(Species)  %>%  # same order as table results  
  select(-Species)  %>%
  kable("html", align = "c") %>%
  kable_styling(full_width = T) %>%
  group_rows(index = setNames(counts, names(counts)),
             label_row_css = "background-color: #666; color: #fff;") 

Upvotes: 1

Ramiro Bentes
Ramiro Bentes

Reputation: 348

Using the iris dataset:

library(tidyverse)
library(kableExtra)

# split the dataset, creating a df for each category from the variable you'll use to group the rows
split_Table <- iris %>%
                split(.$Species) %>%
                discard(function(x) nrow(x) == 0) %>%
                map(., ~ select(., -Species)) # remove Species from split dfs

num_rows <- map(1:length(names(split_Table)), function(x){
             nrow(split_Table[[x]]) 
            }) %>% unlist()  # create function to count frequency of each category

split_Table %>%
 bind_rows() %>%
 kable("html", align = "c") %>%
 kable_styling(full_width = T) %>%
 group_rows(index = setNames(num_rows, names(split_Table)),
            label_row_css = "background-color: #666; color: #fff;") 
# create table with grouped rows

Hope this helps!

Upvotes: 0

Related Questions