如何使 Flextable 中的数字字段为空白

How to make numeric fields in Flextable blank

正如下面的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

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

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

library(dplyr)

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

我会努力将那个案例整合到包中。同时,以下代码允许您为 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