Use backgroundColor in DT package to change a complete row instead of a single value

时间秒杀一切 提交于 2020-01-07 07:46:32

问题


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))



来源:https://stackoverflow.com/questions/38565033/use-backgroundcolor-in-dt-package-to-change-a-complete-row-instead-of-a-single-v

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!