如何使用formattable折叠表中的行值组? [英] How to collapse groups of row values within a table using formattable?
问题描述
我对使用 formattable
R 包中的工具感兴趣,但我只想在表中显示有变化的地方.也就是说,我想要通过 collapse_rows()
函数在 kableExtra
包中提供的分层行标签.
例如,使用kable()
和kableExtra
,我可以这样做:
库(dplyr)图书馆(knitr)图书馆(kableExtra)虹膜%>%group_by(物种)%>%切片(1:2)%>%选择(物种,一切())%>%kable() %>%collapse_rows(1, valign="top")
产生这个:
但是,我想使用 formattable
包和函数来执行此操作,以便我可以在输出期间在特定列上运行任意函数.具体来说,我想添加迷你图"作为新列.我可以使用 knitr
和 formattble
来做到这一点,但据我所知,我丢失了 collapse_rows
.
有没有办法折叠 formattable
中的行?
collapse_rows
编辑 kable 对象.如果您有
如果您对函数中 enquo()
或 quo_name()
的使用感到困惑,您应该查看 dplyr 如何使用非标准求值:
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
?
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()
orquo_name()
within the function, you should check out how dplyr uses Non-standard evaluation: https://dplyr.tidyverse.org/articles/programming.html
这篇关于如何使用formattable折叠表中的行值组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!