Home > Software engineering >  Change the background color of datatable cell based on condition
Change the background color of datatable cell based on condition

Time:02-03

I want to change the background color of every cell of the second column of the datatable when its value is equal to the value of the cell of the same row of the third column of the dataframe in my shiny app.

## app.R ##
library(shiny)
library(shinydashboard)
library(DT)
comp<-structure(list(Source = c("dates1", "dates2", "dates3", "dates4", 
                                "dates5", "dates6", "dates7"), Counts = c(12L, 15L, 17L, 10L, 
                                                                          12L, 7L, 9L), Comparison = c(15, 15, 15, 15, 15, 15, 15), Difference = c(3, 
                                                                                                                                                   0, -2, 5, 3, 8, 6)), row.names = c(NA, -7L), class = "data.frame")


ui <- dashboardPage(
  dashboardHeader(),
  dashboardSidebar(),
  dashboardBody(
    datatableOutput("table")
  )
)

server <- function(input, output) {
  
  output$table<-renderDataTable({
    datatable(comp)
  })
}

shinyApp(ui, server)    

CodePudding user response:

js <- "
function(row, data) {
  if(data[2] == data[3]) {
    $('td:eq(2)', row).css('background-color', 'orange');
  }
}
"

datatable(
  comp, 
  options = list(
    "rowCallback" = JS(js)
  )
)
  •  Tags:  
  • rdt
  • Related