r-markdownflextableofficer

How to use `fp_text_default ` function in flextable package


I see there's a function in flextable package, namely fp_text_default. In help files to this function the only example you can find is

fp_text_default(bold = TRUE)

I was wondering if I can use this function to avoid setting font.size=11 everytime I use custom formatting in my flextables, e.g.

flextable(df) %>%
  compose(value = as_paragraph(
    as_chunk("foo", props = fp_text(shading.color = "orange", font.size=11))
  )) %>%
  compose(value = as_paragraph(
    as_chunk("bar", props = fp_text(bold = TRUE, font.size=11))
  ))

The default font.size param in fp_text is 10 and I always have to set it to 11.

Can fp_text_default be used to set font.size to 11 permaently?


Solution

  • You can use set_flextable_defaults() so that you don't have to call again and again fontsize() or some other functions (i.e. padding, color).

    https://davidgohel.github.io/flextable/reference/set_flextable_defaults.html

    fp_text_default() is a convenient function to overwrite only values that are specified, it keeps other formatting parameters as they are. So far more convenient than fp_text() that force you to specify all params...

    Both can be used together...

    ---
    title: "Untitled"
    output: html_document
    ---
    
    ```{r setup, include=FALSE}
    knitr::opts_chunk$set(echo = TRUE)
    library(flextable)
    library(magrittr)
    set_flextable_defaults(
      font.family = "Arial", font.size = 10,
      padding = 3, border.color = "gray"
    )
    ```
    
    ```{r}
    flextable(head(iris)) %>%
      append_chunks(
        i = 1, j = 1,
        as_chunk(" yo", props = fp_text_default(color = "red"))
      ) %>%
      autofit()
    
    
    flextable(head(mtcars)) %>%
      append_chunks(
        i = 1, j = 1,
        as_chunk(" yo", props = fp_text_default(color = "red"))
      ) %>%
      autofit()
    
    set_flextable_defaults(font.size = 12, padding = 5)
    flextable(head(mtcars)) %>%
      append_chunks(
        i = 1, j = 1,
        as_chunk(" yo", props = fp_text_default(color = "red"))
      ) %>%
      autofit()
    
    ```
    
    
    

    enter image description here