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

冷暖自知 提交于 2019-12-12 13:02:17

问题


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:

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?


回答1:


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()

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



来源:https://stackoverflow.com/questions/51450402/how-to-collapse-groups-of-row-values-within-a-table-using-formattable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!