gpt4 book ai didi

r - 如何使用 formattable 折叠表中的行值组?

转载 作者:行者123 更新时间:2023-12-01 20:19:46 24 4
gpt4 key购买 nike

我有兴趣使用 formattable R 包中的工具,但我只想在表格中显示有更改的地方。也就是说,我想要通过 collapse_rows() 函数在 kableExtra 包中提供分层行标签。

例如,使用 kable()kableExtra,我可以这样做:

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

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

产生这个:

Iris table with rows grouped by Species

但是,我想使用 formattable 包和函数来执行此操作,以便我可以在输出期间对特定列运行任意函数。具体来说,我想添加“迷你图”作为新列。我可以使用 knitrformattble 来做到这一点,但据我所知,我会丢失 collapse_rows

有没有办法折叠formattable中的行?

最佳答案

collapse_rows 编辑 kable 对象。如果您有look at the code ,它根据所选的输出格式(HTML/PDF/文本)执行许多不同的检查。

如果您正在寻找一种更通用的折叠行的方法,我们必须在绘制表格之前编辑 data.frame。我编写了一个函数 collapse_rows_df ,它将折叠数据框中的指定列。

#' 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))
}

使用此函数,输出到格式表:

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

关于r - 如何使用 formattable 折叠表中的行值组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51450402/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com