Search code examples
rgt

Special zero value in gt tables


I'm using the {gt} package to create tables in a report. I would like it so that the "$0.00" currency values are replaced with "-", which is something that's easy to do in Excel but seems surprisingly hard to do with {gt}. Here is an example of a table I would like to have the zero values replaced with something easier on the eyes. The best I can seem to do is use fmt and make a custom function that recreates the entire functionality of fmt_currency, which doesn't seem great.

library(gt)
library(magrittr)
data <- data.frame(x=c(1.23,4.56,0,0,0,0,0))
table <- gt(data) %>%
  fmt_currency(x)

Generated table


Solution

  • I think that gt::text_transform() can solve your immediate problem.

    library(gt)
    library(magrittr)
    data <- data.frame(x=c(1.23,4.56,0,0,0,50,1.5))
    table <- data %>% 
      gt() %>%
      fmt_currency(x)
    
    table
    
    table %>% 
      text_transform(
        locations = cells_body(
          x,
          rows = x==0
        ),
        fn = function(x){
          "-"
        }
      )
    

    Image of gt table where the 0 is replaced with '-'

    Multiple Columns

    If you want to do it across multiple columns, you may want to also wrap it into a function and call against specific columns.

    data <- data.frame(
      x = c( 0, -0.230, 0, -0.445, 0),
      y = c( -0.230, 0.0705, 0.460, -0.686, 0),
      z = c( 0, 0, 0.07, 0.129, -0.68)
    )
    
    currency_dash <- function(gt_data, col_name) {
      text_transform(
        gt_data,
        locations = cells_body(
          columns = {{ col_name }},
          rows = {{ col_name }} == 0
        ),
        fn = function(x) {
          "-"
        }
      )
    }
    
    data %>% 
      gt() %>% 
      fmt_currency(columns = everything()) %>% 
      currency_dash(x) %>% 
      currency_dash(y) %>% 
      currency_dash(z)
    

    Image of multi-column table

    General Transform

    But you'd likely be better suited with just putting the logic into the text_transform().

    data <- data.frame(
      x = c( 0, -0.230, 0, -0.445, 0),
      y = c( -0.230, 0.0705, 0.460, -0.686, 0),
      z = c( 0, 0, 0.07, 0.129, -0.68)
    )
    
    table_currency <- data %>% 
      gt() %>% 
      fmt_currency(everything()) 
    
    table_currency %>% 
      text_transform(
        locations = cells_body(),
        fn = function(x) ifelse(x == "$0.00", "-", x))
      ) 
    
    

    Table output is correct with the map_chr function