Formatting a numeric column as percent in flextable package in R

Viewed 1423

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?

1 Answers

Use set_formatter as documented in the manual, using the iris data (!)


ft_test <- head(iris) %>% flextable() %>% 
  set_formatter( Petal.Width = function(x) sprintf( "%.1f%%", x*100 ) )

Here is the examples section from the manual:


Examples:

     ft <- flextable( head( iris ) )
     ft <- set_formatter( x = ft,
             Sepal.Length = function(x) sprintf("%.02f", x),
             Sepal.Width = function(x) sprintf("%.04f", x)
           )
     ft <- theme_vanilla( ft )
     ft
     

Related