0

I'm trying to format a dataframe rendered by DT (adding color to specifics columns, changing the font, ...), and I was thinking about using the format functions available in DT (i.e. formatStyle, formatCurrency).

However, these functions can only be used on a datatable, and I cannot convert my dataframe to a datatable, as it breaks the different widgets I have inserted in specific columns.

library(shiny)

shinyInput <- function(FUN, len, id, ...) {
  inputs <- character(len)
  for (i in seq_len(len)) {
    inputs[i] <- as.character(FUN(paste0(id, i), ...))
  }
  inputs
}

df <- iris

df$hist <- shinyInput(actionButton, nrow(df), "hist_", label = "Hist", onclick = 'Shiny.onInputChange(\"select_button\",  this.id)' )
df$num <- shinyInput(numericInput, nrow(df), "num_", label = NULL, value=NULL)

ui <- dashboardBody(box(fluidPage(DT::dataTableOutput('DTdf'))))

server <- function(input, output){
  dfDT <- reactive({df})
  output$DTdf <- DT::renderDT(
    dfDT(),  
    escape=F,
    options = list(
      preDrawCallback = JS('function() { Shiny.unbindAll(this.api().table().node()); }'),
      drawCallback = JS('function() { Shiny.bindAll(this.api().table().node()); } ')))
}

shinyApp(ui=ui, server=server)

I tried to replace the first argument of the renderDT function like this, but the widgets stop working.

output$DTdf <- DT::renderDT(
    datatable(dfDT()),  
    escape=F,
    options = list(
      preDrawCallback = JS('function() { Shiny.unbindAll(this.api().table().node()); }'),
      drawCallback = JS('function() { Shiny.bindAll(this.api().table().node()); } ')))

One solution I found to format the columns would be to directly change their content with HTML code, for example if I wanted to changed the fond of the species to bold:

df$Species <- paste0("<div><b>", df$Species, "</b></div>")

But that causes a lot of issues in my program, I'm looking for a solution to only change the visual aspect of the DToutput, not the data in my dataframe.

Erlinska
  • 433
  • 5
  • 16

1 Answers1

1

Try this

server <- function(input, output){
  dfDT <- reactive({df})

  output$DTdf <- DT::renderDT({
    datatable(dfDT(),
    escape=F,
    options = list(
      preDrawCallback = JS('function() { Shiny.unbindAll(this.api().table().node()); }'),
      drawCallback = JS('function() { Shiny.bindAll(this.api().table().node()); } '))) })
}
YBS
  • 19,324
  • 2
  • 9
  • 27