-->

Use backgroundColor in DT package to change a comp

2019-09-04 16:00发布

问题:

The answer is probably obvious but i've been looking into using the backgroundColor attribute in the DT package to change the color of the full row instead of only the value that i use to select the row and I didn't manage to do it.

So basically in my Shiny app, I have a DataTable output in my server file where i wrote this :

output$tableMO <- DT::renderDataTable({
    datatable(DFSurvieMO,
              options = 
                list( displayStart= numerMO()-2,
                      pageLength = 15,
                      lengthChange = FALSE, searching =FALSE),rownames= FALSE) %>% formatStyle(
      c(1:2),
      backgroundColor = 
        if(numerMO()>1) {
          styleInterval(c(DFSurvieMO[,1][numerMO()-1],DFSurvieMO[,1][numerMO()]), c('blank','lightblue', 'blank'))
        }
        else {
          styleInterval(DFSurvieMO[,1][numerMO()], c('lightblue', 'blank'))}

      )
    })

And what i get in my app is a DataTable with only a single cell colored. I tried using target = 'row' but either I didn't put it in the right place or it does not work. So how can i get it to color the whole row ? Thank You.

回答1:

You can write some custom JS function using rowCallback. Below I have written a reactive which will listen to the slider and if the slider values in the mtcars dataset are bigger than your value it will repaint the row. Note that the aData[1] is the column called cyl within the mtcars dataset.

Apologies for not using your code as I wanted to make a more generic example

rm(list = ls())
library(shiny)
library(DT)

ui <- basicPage(
  sliderInput("trigger", "Trigger",min = 0, max = 10, value = 6, step= 1),
  mainPanel(DT::dataTableOutput('my_table'))
)

server <- function(input, output,session) {

  my_callback <- reactive({
    my_callback <- 'function(nRow, aData, iDisplayIndex, iDisplayIndexFull) {if (parseFloat(aData[1]) >= TRIGGER)$("td", nRow).css("background-color", "#9BF59B");}'
    my_callback <- sub("TRIGGER",input$trigger,my_callback)
    my_callback
  })

  output$my_table = DT::renderDataTable(    
    datatable(mtcars,options = list(
      rowCallback = JS(my_callback()),searching = FALSE,paging = FALSE),rownames = FALSE)
  ) 
}
runApp(list(ui = ui, server = server))



标签: r colors shiny dt