Imagine you obtain two flextable
objects and you realize "a posteriori" that you need to combine them horizontally (i.e., you need a function similar to rbind
or bind_rows
, but for flextable
objects). Except for the caption, they have the same structure. Do you know a function or a way to perform this operation?
Next, I share some code to have a reproducible example:
library(dplyr)
library(flextable)
# Simulate some data
g_A <- expand.grid(x = "A", y = c("A_1", "A_2"), z = c("A_1_a", "A_1_b", "A_2_a", "A_2_b"))
g_B <- expand.grid(x = "B", y = c("B_1", "B_2"), z = c("B_1_a", "B_1_b", "B_2_a", "B_2_b"))
g <- rbind(g_A, g_B)
n <- 123
set.seed(1)
df <- sample_n(g, n, replace = TRUE)
# Build the table
tmp <- c(table(df$x)[1],
table(df$y)[1],
table(df$z)[1:2],
table(df$y)[2],
table(df$z)[3:4],
table(df$x)[2],
table(df$y)[3],
table(df$z)[5:6],
table(df$y)[4],
table(df$z)[7:8])
my_tab <- data.frame("tmp" = names(tmp), "counts" = tmp, "percentages" = round(tmp/n*100, 2))
# Split the table
my_tab_A <- my_tab[1:7,]
my_tab_B <- my_tab[-(1:7),]
# flextable A
ft <- flextable(my_tab_A)
ft <- set_header_labels(ft, tmp = "")
ft <- align(ft, align = "center")
ft <- align(ft, j = 1, align = "left")
ft <- set_caption(ft, "Table A")
ft_A <- ft
# flextable B
ft <- flextable(my_tab_B)
ft <- set_header_labels(ft, tmp = "")
ft <- align(ft, align = "center")
ft <- align(ft, j = 1, align = "left")
ft <- set_caption(ft, "Table B")
ft_B <- ft
The solution that I am looking for cannot be based on working with my_tab
because recall that I realize "a posteriori" that I want to combine them horizontally.
Waiting for your insights,
Thanks,
Ciao
this might do the trick...
ft <- flextable( rbind( ft_A$body$dataset, ft_B$body$dataset ) )
ft <- set_header_labels(ft, tmp = "")
ft <- align(ft, align = "center")
ft <- align(ft, j = 1, align = "left")
ft <- set_caption(ft, "Table 1")
ft_C <- ft
ft_C