I would like to produce a table in flextable that groups together certain rows
For example using the data:
df<-structure(list(` ` = c("Group", "Age",
"Residence", "Smoker", "Europe"
), `1` = c("63", "25 ", "25",
"15", "15"), `2` = c("23",
"53 ", "53", "74", "11"),
`3` = c("85", "22", "43",
"13", "15")), row.names = c(NA, -5L), class = c("tbl_df",
"tbl", "data.frame"))
Make table
df<-flextable(df) %>%
add_footer_lines("Observed event") %>%
color(part = "footer", color = "#800000") %>%
bold( bold = TRUE,part="header") %>%
width(j = NULL, width = 1, unit = "in") %>%
autofit()
I would like to add a grouping row above the smoker and Europe rows, called 'demographics'. With longer tables these groupings make it easier to read. There is something similar in kable (group_rows
or pack_rows
) but I haven't found one for flextable.
CodePudding user response:
Maybe you can try something like this:
library(flextable)
# to manipulate data
library(dplyr)
df %>%
# adding a grouping variable
mutate(grouping_var = c('','','','demographics','demographic')) %>%
# define as grouped data
as_grouped_data( groups = c("grouping_var"), columns = NULL) %>%
# equal to your code
flextable() %>%
add_footer_lines("Observed event") %>%
color(part = "footer", color = "#800000") %>%
bold( bold = TRUE,part="header") %>%
width(j = NULL, width = 1, unit = "in") %>%
autofit()
CodePudding user response:
Another possible solution might be to use the ftExtra
library (which extends the functions of the flextable
library). So, please find below a reprex.
Reprex
- Suggested code
library(flextable)
library(ftExtra)
library(dplyr)
grouped_df <- df %>%
mutate(category = c("", "", "", "demographics", "demographics")) %>%
group_by(category) %>%
as_flextable(hide_grouplabel = TRUE) %>%
bold(j = 1, i = ~ !is.na(category), bold = TRUE, part = "body" ) %>%
add_footer_lines("Observed event") %>%
color(part = "footer", color = "#800000") %>%
bold(bold = TRUE, part = "header") %>%
width(j = NULL, width = 1, unit = "in") %>%
autofit()
- Output
grouped_df
Created on 2022-03-29 by the reprex package (v2.0.1)