微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在 flextable 对象的子组中打印汇总统计信息

如何解决在 flextable 对象的子组中打印汇总统计信息

上下文:我正在尝试创建一个包含按组汇总统计信息的 docx 表。

问题:如何在每个组的顶部或底部添加汇总统计信息(例如 sum)并在最后一行得到“总计”行?

到目前为止,我使用 flextable::as_grouped_data() 取得了不错的结果,如下所示:https://davidgohel.github.io/flextable/reference/as_grouped_data.html#see-also

示例:

library(dplyr) # feel free to use data.table if you prefer,I am just more used to dplyr
data_co2_2 <- CO2 %>% 
  group_by(Type,Treatment,conc) %>% 
  summarise(uptake = mean(uptake)) %>% 
  pivot_wider(names_from = Type,values_from = uptake)

data_co2_2 <- as_grouped_data(x = data_co2_2,groups = c("Treatment"))

输出

data_co2
#>     Treatment conc   Quebec Mississippi
#> 1  nonchilled   NA       NA          NA
#> 3        <NA>   95 15.26667    11.30000
#> 4        <NA>  175 30.03333    20.20000
#> 5        <NA>  250 37.40000    27.53333
#> 6        <NA>  350 40.36667    29.90000
#> 7        <NA>  500 39.60000    30.60000
#> 8        <NA>  675 41.50000    30.53333
#> 9        <NA> 1000 43.16667    31.60000
#> 2     chilled   NA       NA          NA
#> 10       <NA>   95 12.86667     9.60000
#> 11       <NA>  175 24.13333    14.76667
#> 12       <NA>  250 34.46667    16.10000
#> 13       <NA>  350 35.80000    16.60000
#> 14       <NA>  500 36.66667    16.63333
#> 15       <NA>  675 37.50000    18.26667
#> 16       <NA> 1000 40.83333    18.73333

预期输出 在“组”行中,我想显示汇总统计数据(如子组的总和),而不是 NA。锦上添花:在表格底部显示“总和”。

解决方法

我想在“组”行中显示汇总统计数据(例如子组的总和),而不是 NA。

如果使用 as_grouped_data() %>% as_flextable(),这是不可能的。显示的值为组名。

以下是一个命题:

library(flextable)
library(dplyr)
library(tidyr)

CO2 <- CO2 %>% 
  mutate(conc = as.character(conc))

agg1 <- CO2 %>% 
  group_by(Type,Treatment,conc) %>% 
  summarise(uptake = mean(uptake),.groups = "drop") 

agg2 <- CO2 %>% 
  group_by(Type,Treatment) %>% 
  summarise(uptake = mean(uptake),.groups = "drop") %>% 
  mutate(conc="Overall")

agg3 <- CO2 %>% 
  group_by(Type) %>% 
  summarise(uptake = mean(uptake),.groups = "drop")  %>% 
  mutate(conc="Overall",Treatment = "Overall")


all_data <- bind_rows(agg1,agg2,agg3) %>% 
  arrange(Type,conc) %>% 
  pivot_wider(names_from = Type,values_from = uptake)

as_grouped_data(x = all_data,groups = c("Treatment")) %>% 
  as_flextable() %>% 
  compose(i = ~ is.na(conc) & is.na(Treatment),j = "conc",value = as_paragraph("avg for all conc")) %>% 
  compose(i = ~ is.na(conc) & is.na(Treatment),value = as_paragraph("avg for all conc")) %>% 
  bold(bold = TRUE,i = ~!is.na(Treatment)) %>% 
  color(i= ~ conc %in% "Overall",color = "red") %>% 
  colformat_double(j = c("Quebec","Mississippi"),digits = 1) 

enter image description here

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。