Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Way to merge flextables and retain formatting

Tags:

r

flextable

Say I have 2 flextables:

ft1 <- regulartable(head(iris))
ft2 <- regulartable(tail(iris))

And they have distinct formatting:

ft1 <- bg(ft1, bg="green")
ft2 <- color(ft2, color = "blue")

Is there a way to merge these two after they are already flextables, and keep the formatting?

I can merge them using this:

ft3 <- regulartable(rbind(ft1$body$dataset, ft2$body$dataset))

but I lose all formatting.

I understand it would be easier to merge the dataframes before converting to flextables, but the way my actual data is generated makes that difficult as the two flextables I'm trying to merge are the result of other functions I've written.

Edit:

The aim is to keep the individual formatting, like this:

enter image description here

like image 364
morgan121 Avatar asked Nov 06 '22 20:11

morgan121


1 Answers

Not very elegant but might get the job done...

library(flextable)
library(magrittr)

ft1 <- regulartable(head(iris))
ft2 <- regulartable(tail(iris))

ft_formatting <- function(ft1, ft2,
                          color1 = "black", bg1 = "white", color2 = "black", bg2 = "white") {
  n_row1 <- nrow(ft1$body$dataset)
  n_row2 <- nrow(ft2$body$dataset)

  n_col1 <- ncol(ft1$body$dataset)
  n_col2 <- ncol(ft2$body$dataset)

  i_1 <- 1:n_row1
  i_2 <- n_row1+1:n_row2

  regulartable(rbind(ft1$body$dataset, ft2$body$dataset)) %>%
    bg(i = i_1, j = 1:5, bg = bg1) %>%
    color(i = i_1, j = 1:n_col1, color = color1) %>%
    bg(i = i_2, j = 1:5, bg = bg2) %>%
    color(i = i_2, j = 1:n_col2, color = color2)

}

ft_formatting(ft1, ft2, bg1 = "green", color2 = "blue")
like image 137
plant Avatar answered Nov 15 '22 13:11

plant