在 R 中的 flextable 包中将数字列格式化为百分比
Formatting a numeric column as percent in flextable package in R
例如我正在使用虹膜数据:
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)
如果我希望使用百分比格式的“Petal.Width”值,正确的语法是什么?我找不到 colformat_percent 函数。有没有办法用灵活的语法来弥补?
按照手册中的说明使用 set_formatter
,使用虹膜数据 (!)
ft_test <- head(iris) %>% flextable() %>%
set_formatter( Petal.Width = function(x) sprintf( "%.1f%%", x*100 ) )
这是 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
例如我正在使用虹膜数据:
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)
如果我希望使用百分比格式的“Petal.Width”值,正确的语法是什么?我找不到 colformat_percent 函数。有没有办法用灵活的语法来弥补?
按照手册中的说明使用 set_formatter
,使用虹膜数据 (!)
ft_test <- head(iris) %>% flextable() %>%
set_formatter( Petal.Width = function(x) sprintf( "%.1f%%", x*100 ) )
这是 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