【问题标题】:How to make numeric fields in Flextable blank如何将 Flextable 中的数字字段设为空白
【发布时间】:2018-01-31 19:34:52
【问题描述】:

如以下 MWE 所示,Amount of Bananas 中的 NA 如何变为空白而不是显示“NA”?我希望数字列像字符列一样工作(请参阅 MWE 中的苹果颜色)。

library(data.table)
library(flextable)
the.data <- data.table(Fruit=c("Apples", "Oranges", "Bananas", "Pears"), Amount=c(4L, 8L, NA_integer_, 2L), Color=c(NA_character_, "Orange", "Yellow", "Green"))
the.ft <- flextable(the.data)
the.ft

一种方法是将数字列转换为字符,但也许有更好的方法。

【问题讨论】:

    标签: r flextable


    【解决方案1】:

    我将努力将这个案例整合到包装中。同时,以下代码可让您为 NA 显示空白。

    library(flextable)
    the.data <- data.table(
      Fruit=c("Apples", "Oranges", "Bananas", "Pears"), 
      Amount=c(4L, 8L, NA_integer_, 2L), 
      Color=c(NA_character_, "Orange", "Yellow", "Green"))
    
    the.ft <- regulartable(the.data)
    the.ft <- set_formatter(
      the.ft, 
      Amount = function(x) ifelse(is.na(x), "", sprintf("%d", x) ),
      Color = function(x) ifelse(is.na(x), "", x )  
      )
    the.ft
    

    【讨论】:

    • 太棒了,感谢Officer+Flextable+RVG 的精彩套餐!
    【解决方案2】:

    本周早些时候我也在想同样的事情,但在flextable 中没有找到直接的方法来做到这一点。同时,此代码使用管道将Amount 转换为字符,并在此过程中保留了原始数据帧的列类型。

    library(dplyr)
    
    the.data %>%
             mutate(Amount = if_else(is.na(Amount), "", as.character(Amount))) %>%
             flextable()
    

    【讨论】:

      猜你喜欢
      • 2011-05-25
      • 2013-02-19
      • 2023-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多