使用flextable r包格式化多个列

时间:2018-03-23 19:19:46

标签: r flextable

是否可以使用flexitable以一行脚本格式化多列?

该示例包含两种不同类型的double的变量。我想:

  1. 将大于1000的变量舍入到最接近的1000并添加千位逗号格式,
  2. 小于一到两位小数的圆形变量
  3. 使用flextable这是相对简单的,但是变成了具有更大数据集的孔。我找不到更有效率的方法。

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

    MWE

    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")
    

    Final table

1 个答案:

答案 0 :(得分:1)

是的,可以在此处找到文档: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))