10
votes

How could one add a caption to a flextable rendered to docx? EDIT: The aim is to produce a proper caption which can be referenced within the document to produce a list of tables and inline references.

iris.t <-
  iris[1:5,] %>%
  regulartable() %>% 
  style(pr_c = officer::fp_cell(vertical.align = "bottom",
                                border.bottom = officer::fp_border(width = 2)), part = "header") %>% 
  rotate(j = names(iris)[-c(1:2)],
         rotation = "tbrl", part = "header", align = "bottom") %>% 
  height(height = max(dim_pretty(., part = "header")$widths), part = "header") %>% 
  width(width = dim_pretty(.,part = "body")$widths)

iris.t 
1
you can find the doc about headers and footers here: davidgohel.github.io/flextable/articles/…, a caption is text in a footer or header row.David Gohel
This does not render a proper caption which could be included in an autogenerated list of tables or referenced. I have updated the post to reflect this need.JAllen
I was just looking at that article! Trying to figure it out. Is this approach compatible with knitr/rmarkdown? It appears to start with a fresh docx file. looking at shortcuts$slip_in_tableref and slip_in_seqfield seems to have what would be needed.JAllen
@David Gohel It would be nice to have an example how to create a caption in .Rmd. I have not been able to figure out how to add body_add_par(value = "data iris", style = "table title")` in a Rmarkdown fileDieter Menne

1 Answers

3
votes

I use the following way to caption tables.

#set the table caption styling
knitr::opts_chunk$set(tab.cap.pre = "Table ", tab.cap.sep = ": ")

#set the table caption styling
set_flextable_defaults(font.family = "Calibri (Body)",
                       font.size = 9, 
                       digits = 0, 
                       border.color = "#000000",
                       padding.bottom = 1,
                       padding.top = 1,
                       padding.left = 3,
                       padding.right = 1)

ft <- flextable(df, defaults = TRUE) #convert to flextable object
autonum <- run_autonum(seq_id = "tab", bkm = "TC1", bkm_all = TRUE) # number the table, bkm (bookmark) is important as the cross-referencing is done using the bookmark
ft <- set_caption(ft, caption = "Traffic Counts for Existing Condition", 
                  style = "Table Caption", autonum = autonum)
ft # to print the table

to cross-reference the table use \@ref(tab:TC1)

to produce a list of tables use

<!---BLOCK_TOC{seq_id: 'tab'}--->