Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to collapse groups of row values within a table using formattable?

I am interested in using tools within the formattable R package, but I want to only shows in the table where there is a change. That is, I want hierarchical row labeling that is offered in the kableExtra package via the collapse_rows() function.

For example, using kable() and kableExtra, I can do this:

library(dplyr)
library(knitr)
library(kableExtra) 

iris %>% 
  group_by(Species) %>% 
  slice(1:2) %>% 
  select(Species, everything()) %>% 
  kable() %>% 
  collapse_rows(1, valign="top")

to produce this:

Iris table with rows grouped by Species

However, I would like to do this using the formattable package and function so that I can run an arbitrary function over specific colums during output. Specifically, I want to add "sparklines" as a new column. I can do that using knitr and formattble, but then I lose the collapse_rows, as far as I can tell.

Is there any way to collapse rows in formattable?

like image 558
Kalin Avatar asked Jul 20 '18 21:07

Kalin


Video Answer


1 Answers

collapse_rows edits the kable object. If you have a look at the code, it does a lot of different checks depending on the output format selected (HTML/PDF/text).

If you are looking for a more general method of collapsing the rows, we will have to edit the data.frame before the table is plotted. I have written a function collapse_rows_df which will collapse a specified column within your dataframe.

#' Collapse the values within a grouped dataframe
#' 
#' 
collapse_rows_df <- function(df, variable){

  group_var <- enquo(variable)

  df %>%
    group_by(!! group_var) %>%
    mutate(groupRow = 1:n()) %>%
    ungroup() %>%
    mutate(!!quo_name(group_var) := ifelse(groupRow == 1, as.character(!! group_var), "")) %>%
    select(-c(groupRow))
}

Using this function, outputting to the formattable:

iris %>% 
  group_by(Species) %>% 
  slice(1:2) %>% 
  select(Species, everything()) %>%
  collapse_rows_df(Species) %>%
  formattable()

enter image description here

If you are confused by the use of enquo() or quo_name() within the function, you should check out how dplyr uses Non-standard evaluation: https://dplyr.tidyverse.org/articles/programming.html

like image 58
Michael Harper Avatar answered Sep 19 '22 10:09

Michael Harper