简体   繁体   中英

R Shiny: Get DT row background color on top of column background color

I am using DT::renderDT in a shiny app and am formatting background color for certain columns and rows. I need the row background color to be on top of column background color. I tried switching order of formatStyle but that didn't work. Here's a small example -

library(shiny)
library(DT)

shinyApp(
  ui = fluidPage(
    DTOutput("table")
  ),
  server = function(input, output, session) {    
    output$table <- renderDT({
      head(iris) %>%
        datatable() %>%
        formatStyle(c(2,4), backgroundColor = "#fcf4d9") %>%
        formatStyle(1, target = 'row', 
          backgroundColor = styleEqual(c(4.7, 5), c("#fc8a8a", "#fc8a8a"))
          # comment above row and ucomment below row for row color using styleInterval()
          # backgroundColor = styleInterval(c(0, 5, 9), c('blue', 'green', 'red', 'orange'))

        )
    })
  }
)

Result (incorrect) with styleEqual() -

例如styleEqual

Result (incorrect) with StyleInterval() -

styleInterval的示例

The row colors need to be on top of yellow (column color).

Looking for a generalized solution that would work for multiple rows and with styleEqual() or styleInterval() . Any help is appreciated. Thanks!

Here is a solution:

rowCallback <- c(
  "function(row, data, displayNum, displayIndex, dataIndex){",
  "  if(data[1] === 4.7){",
  "    $(row).find('td').addClass('red');",
  "  }",
  "}"
)

shinyApp(
  ui = fluidPage(
    tags$head(
      tags$style(
        HTML(
          "table.dataTable tbody tr td.red {background-color: #fc8a8a !important}"
        )
      )
    ),
    DTOutput("table")
  ),
  server = function(input, output, session) {    
    output$table <- renderDT({
      head(iris) %>%
        datatable(options = list(rowCallback = JS(rowCallback))) %>%
        formatStyle(c(2,4), backgroundColor = "#fcf4d9")
    })
  }
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM