Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding headers IN table in flextable

I am trying to use flextable to make a nice table that knits into word, with descriptive banners/headers through out

Example data:

trialdata<-structure(list(` ` = c("Number per team", "Average height", "vegetarian", 
"meat", "carrot", "cucumber", "orange", 
"banana", "pepper", "tangerine", "Average Score", 
"Range Score", "Number of children", "Number of parents", 
"Number of grandparents"), `year 1` = c("20", "2", 
"25", "12", "4", "7", 
"7", "37", "21", "3", 
"-0.3", "78 : 1", "61", "19", 
"39"), `Year 2` = c("98", "28.2", "23", 
"1", "8", "6", "1", 
"36", "2", "29", "-0.2", "3 : 2", 
"6", "18", "9"), `Year 3` = c("88", 
"28.2", "24", "1", "1", "4", 
"91", "3", "24 ", "2", 
"-0.2", "7 : 2", "58", "1", 
"8")), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, 
-15L))

Make a table:

  install.packages("flextable")
library(flextable)
table1<-flextable(trialdata)

That makes a table which looks like the below picture, with a single header table looks like

However I would like to add some kind of descriptive header, e.g.'favorite food'. This is not a 'grouping' already in the data, but an added text I would like to make the table clearer, for example to look like this:

Ideal tabke

Flex table has ways to add headers and footers, but I can't see a way to add a header-type object in the table.

like image 328
Gabriella Avatar asked May 29 '26 22:05

Gabriella


1 Answers

There is a solution I can think about with as_grouped_data() |> as_flextable():

library(flextable)
trialdata <- structure(list(` ` = c(
  "Number per team", "Average height", "vegetarian",
  "meat", "carrot", "cucumber", "orange",
  "banana", "pepper", "tangerine", "Average Score",
  "Range Score", "Number of children", "Number of parents",
  "Number of grandparents"
), `year 1` = c(
  "20", "2",
  "25", "12", "4", "7",
  "7", "37", "21", "3",
  "-0.3", "78 : 1", "61", "19",
  "39"
), `Year 2` = c(
  "98", "28.2", "23",
  "1", "8", "6", "1",
  "36", "2", "29", "-0.2", "3 : 2",
  "6", "18", "9"
), `Year 3` = c(
  "88",
  "28.2", "24", "1", "1", "4",
  "91", "3", "24 ", "2",
  "-0.2", "7 : 2", "58", "1",
  "8"
)), class = c("tbl_df", "tbl", "data.frame"), row.names = c(
  NA,
  -15L
))

trialdata$group <- c(rep("blah", 4), rep("Favorite foods", 11))

as_grouped_data(trialdata, groups = "group") |> 
  as_flextable() |> 
  align(i = ~ !is.na(group), align = "center")

There are other solutions like using tabulator() but for this, data should be tidy.

enter image description here

like image 85
David Gohel Avatar answered May 31 '26 14:05

David Gohel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!