使用 flextable r 包格式化多列

Pet*_*ter 6 r flextable

是否可以使用灵活的一行脚本来格式化多列?

该示例包括两种不同类型的双精度变量。我想:

  1. 将大于 1000 的变量舍入到最接近的 1000 并添加千位逗号格式,以及
  2. 舍入变量小于一到两位小数

使用 flextable 这相对简单,但会变成一个包含更大数据集的钻孔。我看不出有什么方法可以更有效地做到这一点。

我可以使用 dplyr 来预处理数据(尽管逗号格式需要将变量类型从 double 更改为 character)。如果可能的话,我更喜欢在 flextable 中做到这一点。我知道 Huxtable 可以进行多列格式化。用户是否可以创建定制的 set_formatter_type 函数?

移动电源

set.seed(100)

tib <- tibble(a = letters[1:4],
              b = runif(4)*sample(c(10000, 1000000, 10000000), 4, replace = TRUE),
              c = runif(4)*sample(c(10000, 1000000, 10000000), 4, replace = TRUE),
              d = runif(4)*sample(c(10000, 1000000, 10000000), 4, replace = TRUE),
              e = runif(4),
              f = runif(4))


  regulartable(tib) %>%
  set_formatter(b = function(x) format(round(x, -3), big.mark = ",")) %>% 
  set_formatter(c = function(x) format(round(x, -3), big.mark = ",")) %>% 
  set_formatter(d = function(x) format(round(x, -3), big.mark = ",")) %>% 
  set_formatter(e = function(x) round(x, 2)) %>%
  set_formatter(f = function(x) round(x, 2)) %>%
  print(preview = "docx")
Run Code Online (Sandbox Code Playgroud)

决赛桌

Dav*_*hel 3

是的,可以在这里找到文档: https: //davidgohel.github.io/flextable/articles/format.html#set_formatter-function

在这里: https: //davidgohel.github.io/flextable/reference/set_formatter.html

set_formatter(b = function(x) format(round(x, -3), big.mark = ","), 
              c = function(x) format(round(x, -3), big.mark = ","), 
              d = function(x) format(round(x, -3), big.mark = ","), 
              e = function(x) round(x, 2), 
              f = function(x) round(x, 2))
Run Code Online (Sandbox Code Playgroud)

  • @Tjebo这些新功能应该有所帮助:) https://github.com/davidgohel/flextable/blob/master/R/formatters.R#L74 (3认同)