Search code examples
rflextable

How to make numeric fields in Flextable blank


As demonstrated in the following MWE, how can the NA at Amount of Bananas become blank instead of showing "NA"? I would like the numeric columns to work like the character columns (see Color for Apples in the 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

One way could be to convert the numeric column to character, but maybe there is a better way.


Solution

  • I will work on integrating that case in the package. Meanwhile, the following code lets you display blank for 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