使用Dplyr和Flextable进行行求和

djmepvbi  于 2023-06-19  发布在  其他
关注(0)|答案(1)|浏览(128)

我有以下dataframe:

structure(list(Annee = c("2021-2022 ", "2021-2022 ", "2021-2022 ", 
"2022-2023 ", "2022-2023 ", "2022-2023 ", "2022-2023 "), Niveau = c("CE1", 
"CP", "CP", "CE1", "CE1", "CP", "CP"), Sexe = c("Garçons", "Filles", 
"Garçons", "Filles", "Garçons", "Filles", "Garçons"), Effectifs = c(4, 
1, 2, 1, 2, 4, 3)), row.names = c(NA, -7L), class = "data.frame")

我用flextable做了一个表:

data %>%
  pivot_wider(names_from=Annee, values_from=c(`Effectifs`)) %>%
  replace(is.na(.), 0) %>%
  arrange(match(Sexe, c("Filles", "Garçons"))) %>%
  arrange(match(Niveau, c("CP", "CE1"))) %>%
  flextable::flextable() %>% 
  flextable::align(align = "center", part = "all") %>%
  theme_zebra()%>%
  merge_v(j = c("Niveau"))%>%
  border_outer(part = "all") %>%
  hline_top(part = "header") %>%
  hline(part="body")%>%
  align(align = "center", part = "header") %>% 
  border_inner_v(part = "all")%>% 
  valign(valign = "center", part = "header")%>% 
  fix_border_issues(part = "all")

这给予了我这个结果:

我需要在flextable中添加一个新行,它将是每个“Niveau”的“Effectifs”的总和。下面是预期的结果:

提前感谢您的帮助!

sbdsn5lh

sbdsn5lh1#

使用一个小的自定义函数将总计行添加到您的数据中,您可以执行以下操作:

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

add_total <- \(x) {
  x %>%
    group_by(Niveau) %>%
    summarise(Sexe = "Total", across(where(is.numeric), sum)) %>%
    bind_rows(x)
}

data %>%
  pivot_wider(names_from = Annee, values_from = c(`Effectifs`)) %>%
  replace(is.na(.), 0) %>%
  add_total() %>%
  arrange(match(Sexe, c("Filles", "Garçons", "Total"))) %>%
  arrange(match(Niveau, c("CP", "CE1"))) %>%
  flextable::flextable() %>%
  flextable::align(align = "center", part = "all") %>%
  theme_zebra() %>%
  merge_v(j = c("Niveau")) %>%
  border_outer(part = "all") %>%
  hline_top(part = "header") %>%
  hline(part = "body") %>%
  align(align = "center", part = "header") %>%
  border_inner_v(part = "all") %>%
  valign(valign = "center", part = "header") %>%
  fix_border_issues(part = "all") %>%
  bold(i = ~ Sexe == "Total")

相关问题