rflextableofficer

Formatting a numeric column as percent in flextable package in R


For example I am using iris data:

library(flextable)
library(officer)
library(magrittr)

ft_test <- head(iris) %>% flextable() %>% 
  colformat_num(j = c("Sepal.Length", "Sepal.Width",
                             "Petal.Length", "Petal.Width"), digits = 1)

What would be the proper syntax if I wish to have "Petal.Width" values in percent format? I could not find colformat_percent function. Is there a way to make up for it using flextable syntax?


Solution

  • It seems there is an official function fmt_pct.

    ft_test <- head(iris) %>% flextable() %>% mk_par(
      j = "Sepal.Length",
      value = as_paragraph(as_chunk(Sepal.Length, formatter = fmt_pct)))
    

    Alternatively, you can format the cells into characters before converting it to a flextable:

    percent <- function(x, digits = 2, format = "f", ...) {    
      paste0(formatC(x * 100, format = format, digits = digits, ...), "%")
    }
    
    ft_test <- head(iris) %>% 
      mutate(across(where(is.numeric), ~percent(.x))) %>%
      flextable()