JJJ
JJJ

Reputation: 1029

R shiny; globally define NA behaviour in renders

When making a Shiny app with many tables containing some NA values, it might be helpful to globally define how NA's get printed by, for example, renderTable.

To provide an example:

library(shiny)
ui <- fluidPage(
  column(2,uiOutput("ourTable")),
  column(2,uiOutput("ourTable2"))
)

server <- function(input, output) {
  data<-data.frame(A=1:6, B=LETTERS[11:16], C=c(1,2,"A", "B", NA, NA))
  output$ourTable<-renderTable({data})
  output$ourTable2<-renderTable({data}, na="")
}

shinyApp(ui = ui, server = server)

This renders like this:

enter image description here

Ideally, I would like to add a line of code (either in server or in ui) so that all tables render like ourTable2, that is, without the NA being printed in the output and without having to explicitly specify this for each table I add.

Upvotes: 0

Views: 122

Answers (2)

JJJ
JJJ

Reputation: 1029

Per Ricardo's comment under my question I wrote the following wrapper which does the trick for all rendered tables (but not other ways of outputting tables):

renderTableNew<-function(x){renderTable({x}, na="")}

Obviously, this 'trick' can be used to define more arguments of renderTable() and multiple such functions can be created with different parameters. When using this, the only thing to be wary about is that you'd have to use renderTableNew()instead of renderTable.

Upvotes: 0

Soren
Soren

Reputation: 2445

You can define the following in your global.R file (or within the server.R) file if you prefer. Which will work on your tables and also return "" if the entire table is NA. If you pass complex objects like embedded lists of lists, it would need to be a bit more sophisticated. However, printing data.frame as in the OP will work.

in global.R (or elsewhere):

format.NAs <- function(x) {
  if (identical(x,NA)) return ("")
  x <- as.data.frame(lapply(df,unclass)) #to accommodate factors()
  x[is.na(x)] <- ""
  return (x)
}

In your server.r (or UI modules or where needed)

 output$ourTable2<-renderTable({format.NAs(data)})

A generic example:

df <- data.frame(A=c(2,4,6,8),B=c(1,NA,9,7),C=c("test",NA,"test1",NA),stringsAsFactors = F)
> format.NAs(df)
  A B     C
1 2 1  test
2 4        
3 6 9 test1
4 8 7      

Upvotes: 1

Related Questions