Customizing how DataTables displays missing values in Shiny [duplicate]
Asked Answered
S

2

6

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

Sheeran answered 23/10, 2019 at 15:13 Comment(0)
O
10

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

Ovoviviparous answered 23/10, 2019 at 15:43 Comment(5)
Perfect, thanks! I can see how this lets you apply any arbitrary CSS to just the missing values.Sheeran
What to do to not display the rows containing NA/Missing valuesBoult
This won't work if there are hidden columns, data[I] refer to the i-th col in the data while 'td:eq('+i+')' refers to the i-th visible column when displaying the DT first.Kid
Good remark @moodymudskipper. That should work however if the hidden columns are at the end.Forefinger
in part. but if they are themselves NA they won't be formatted once shown.Kid
D
3

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.

Donor answered 23/10, 2019 at 15:29 Comment(1)
Thanks! That is something, though, looking at toJSON(), it looks like it can only give us unformatted "NA"s instead of blanks.Sheeran

© 2022 - 2024 — McMap. All rights reserved.