2

I'm using renderDataTable in my shiny app to display the contents of a data.table vals$content4table which is a reactiveValues.

It can happen that the vals$content4table is equal to a datatable with no columns. In that case i have an error while using formatCurrency because it searches for a column that does not exist. Is there any way to check if the datatable has columns with ifelse to avoid the error?

Here is a piece of my code of my server.

#initialising vals$content4table when launching the app
 vals <- reactiveValues(content4table = if(someBoolean) {data.table(NULL)} else {data.table("Column1" = "whatever","Currency" = 1000}
  )
 
output$TableInUI <- DT::renderDataTable(datatable(vals$content4table) %>% ifelse(nrow(vals$content4table)>0,formatCurrency(2, currency = "", interval = 3, mark = ",",  digits = 0),fnothing()))

#where fnothing is defined as
fnothing<-function(df) return(df)

The above code doesn't work and gives this error: Warning: Error in ifelse: unused argument (fnothing())

Mario
  • 137
  • 1
  • 10

1 Answers1

0

You could use req:

output$TableInUI <- DT::renderDataTable({
   req(isTRUE(ncol(vals$content4table)>0))
   vals$content4table
})
Waldi
  • 39,242
  • 6
  • 30
  • 78
  • This solutions skips completely the problem with formatCurrency where actually the problem is originating. In case of no columns or no rows the datatable simply does not get displayed which is perfectly fine. – Mario Sep 16 '20 at 15:15
  • @Mario, should I understand that it solved the problem or that it didn't solve the right problem? – Waldi Sep 16 '20 at 16:16
  • You did not. After adding the line req(isTRUE(ncol(vals$content4table)>0)) the tool crashes instanstly whatever the number of columns or rows vals$content4table has. – Mario Sep 16 '20 at 16:48
  • this is quite surprising, because `req` normally works fine, and `isTRUE(ncol(data.table::data.table(NULL)) > 0)` returns FALSE. – Waldi Sep 16 '20 at 17:14