Customizing how DataTables displays missing values in Shiny

Viewed 1151

DataTables, in Shiny, displays missing values as blank space. Is there a way to change that? I'm dreaming especially of the gray, italicized NAs that RStudio uses in its data viewer. I'd have no problem with injecting such strings into character columns for display purposes, but, of course, sometimes the columns are numeric, or date, and converting them just for display seems problematic.

MWE of DT's default missing values display:

library(DT)
library(shiny)

ui <- fluidPage(
    dataTableOutput("airquality")
)

server <- function(input, output) {
    output$airquality <- renderDataTable(airquality)
}

shinyApp(ui = ui, server = server)

default_dt_display

2 Answers

You can do:

library(DT)

rowCallback <- c(
    "function(row, data){",
    "  for(var i=0; i<data.length; i++){",
    "    if(data[i] === null){",
    "      $('td:eq('+i+')', row).html('NA')",
    "        .css({'color': 'rgb(151,151,151)', 'font-style': 'italic'});",
    "    }",
    "  }",
    "}"  
  )

datatable(airquality, options = list(rowCallback = JS(rowCallback)))

enter image description here

Customizing one of the options might be a good start:

options(htmlwidgets.TOJSON_ARGS = list(na = 'string'))

Here's the source so you can read the complete thread about this issue and its workarounds.

Related