Chris
Chris

Reputation: 2256

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.

Upvotes: 2

Views: 1551

Answers (2)

David Gohel
David Gohel

Reputation: 10675

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

Upvotes: 6

tifu
tifu

Reputation: 1411

I was wondering the same thing earlier this week and haven't found a straightforward way to do this within flextable. In the meantime, this code converts Amount to character using a pipe, and in doing so preserves the column types of the original data frame.

library(dplyr)

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

enter image description here

Upvotes: 3

Related Questions