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

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:

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.
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.

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