Using the "flextable" package in R how do I insert a table into one of the cells of a flex table?

166 Views Asked by At

I am trying to create a Microsoft Word document table using the R flextable package.

My attempt:

library(flextable)
library(dplyr)
# create flextables
Outer_table <- data.frame(Number = c(1,2), 
                          table = c(NA,NA)) %>% flextable()
df1 <- data.frame(Species = c("Maple", "Oak", "Hemlock", "Red Pine"),
                  Age = c(40,37,52,64)) %>% flextable()

# combine flextables
Outer_table <- Outer_table %>%
  flextable::compose(j ="Table", i = 1,value = df1)

This results in an error

Error in x$data[i,j] <- value: number of items to replace is not a multible of replacement length.

  1. What would be a way of properly fomrating the smaler dfs to create a table such as this?
  2. Additionaly, how would I go about adding in the text "Table of Average Tree Ages by Species" above the table?
1

There are 1 best solutions below

0
On

Maybe, this gets you started. I think {officer} offers help:

library(flextable)
library(officer)

# reformated data 
t1 <- data.frame(Number = c(1, 2), 
                 table = c(NA, NA)) |> 
  flextable() |> theme_box()                  
t2 <- data.frame(Species = c("Maple", "Oak", "Hemlock", "Red Pine"), 
                 Age = c(40, 37, 52, 64)) |> 
  flextable() |> theme_box()

# create docx object 
read_docx() |>
  body_add_par("A table of sth.") |> 
  body_add_flextable(value = t1) |>
  body_add_par("Another table of sth.") |>
  body_add_flextable(value = t2) |>
  print(target = "example.docx")
# you will find example.docx in your current working directory 

I expect that further styling can be achieved with body_add_*()-functions, see here.