Search code examples
rms-wordr-markdownflextable

Set caption for flextable objects with align, font and italic in Rmarkdown of Word output


My little example is as follows:

---
output:
  word_document: default
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE, message = FALSE, warning = FALSE)
```

```{r}
library(flextable)
set_flextable_defaults(
  font.family = "Arial", 
  font.size = 9, 
  big.mark = "",
  theme_fun = "theme_vanilla"
)
library(magrittr) ### for %>%
ft = head(mtcars[,1:5]) %>% flextable() %>% 
  set_caption(caption = "display a subset of columns for mtcars data") %>%
  # align(part = "caption", align = "center") %>%
  # font(part = "caption", fontname = "Calibri") %>%
  # italic(italic = FALSE, part = "caption") %>%
  add_footer_lines("also can be based on optional argument col_keys") %>%
  font(part = "footer", fontname = "Consolas") %>%
  bold(bold = TRUE, part = "footer")
ft
```

The Word Rmarkdown output shows the caption with left-alignment, Cambria-font and italic. I want to customize the caption part for the table with center-alignment, some-other-font and no-italic. However, the flextable package has no part for caption, with partname of the table (one of ’all’, ’body’, ’header’, ’footer’). How can I achieve the goal?


Solution

  • This is only available in the development version for now:

    New features have been added recently:

    • paragraph settings
    • ability to define a complex paragraph with different formats for chunks
    ---
    output:
      word_document: default
    ---
    
    ```{r setup, include=FALSE}
    knitr::opts_chunk$set(echo = FALSE, message = FALSE, warning = FALSE)
    library(flextable)
    library(officer)
    set_flextable_defaults(
      font.family = "Arial", 
      font.size = 9, 
      big.mark = "",
      theme_fun = "theme_vanilla"
    )
    ```
    
    ```{r}
    ft = head(mtcars[,1:5]) |> flextable() |> 
      set_caption(
        caption = as_paragraph(
          as_chunk("display a subset of columns", 
                   props = fp_text_default(font.family = "Courier", bold = FALSE)),
          as_chunk(" for mtcars data", 
                   props = fp_text_default(color = "red", font.family = "Helvetica", bold = TRUE))
          ),
        fp_p = fp_par(text.align = "center", padding = 5)
      ) |>
      add_footer_lines("blah blah blah") |>
      font(part = "footer", fontname = "Consolas") |>
      bold(bold = TRUE, part = "footer")
    ft
    ```
    
    

    enter image description here


    to install the current dev version:

    remotes::install_github("davidgohel/officer")
    remotes::install_github("davidgohel/flextable")