Home > Software engineering >  Changing how zeros are printed in sparse tables using `flextable`
Changing how zeros are printed in sparse tables using `flextable`

Time:12-18

I have used kable() from knitr to generate nice-looking tables outputted in Microsoft Word. However, kable() was designed to be a simple table generator and can't offer all the advanced features that flextable has; for instance, the inclusion of a footer.

Sometimes, I want to print an overly sparse table and include it in a Microsoft Word document. Instead of printing zeros, I want to suppress them using the zero.print argument in prettyNum().

For a kable, I can add a format.arg() argument to specify whether to print the zeros (which is passed to format() and then passed to prettyNum().

Could a similar feature be added in flextable? This would enable flextable to do all the things a kable can do and then some, making it a worthwhile package. Probably the best function to add would be colformat_num(). Could an ... argument be added that passes additional arguments to prettyNum() or formatC()?

  A <- tibble::as_tibble(matrix(c(rep(0, 9), rep(1,3)), nrow = 4, dimnames = list(NULL, LETTERS[1:3])))

knitr::kable(A, caption = "Example -- with zeros")
A   B   C
0   0   0
0   0   1
0   0   1
0   0   1
Example – with zeros

knitr::kable(A, caption = "Example -- zeros suppresed. A pattern in this example table is more easy to spot",
             format.args = list(zero.print = ".")  #Make all the zeros be a dot.
)
A   B   C
.   .   .
.   .   1
.   .   1
.   .   1
Example – zeros suppressed. A pattern in this example table is easier to spot

flextable::flextable(A)

CodePudding user response:

We can prepare our data before wrapping with flextable package.

```{r}
library(tidyverse)
library(flextable)

A <- tibble::as_tibble(matrix(c(rep(0, 9), rep(1,3)), nrow = 4, dimnames = list(NULL, LETTERS[1:3])))


A1 <- A %>% mutate_if(is.numeric, str_replace_all, pattern = "0", replacement = ".")


flextable(A1) %>% 
  set_caption(., "I'm a beautiful table")
```  

enter image description here

CodePudding user response:

You can use any defined formatter and use it with function set_formatter().

library(tidyverse)
library(flextable)

A <- tibble::as_tibble(matrix(c(rep(0, 9), rep(1,3)), nrow = 4, dimnames = list(NULL, LETTERS[1:3])))

fun <- function(x) {
  z <- formatC(x)
  z[x < 0.001] <- "."
  z
}
fun_all_cols <- lapply(colnames(A), function(x) fun)
names(fun_all_cols) <- colnames(A)

flextable(A) %>% 
  set_formatter(values = fun_all_cols)

enter image description here

  • Related