Reputation: 714
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?
Upvotes: 8
Views: 4220
Reputation: 5429
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
Upvotes: 10
Reputation: 883
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()
Upvotes: 3