firmo23
firmo23

Reputation: 8454

Change the background color of datatable cell based on condition

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)    

Upvotes: 1

Views: 539

Answers (1)

St&#233;phane Laurent
St&#233;phane Laurent

Reputation: 84719

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

datatable(
  comp, 
  options = list(
    "rowCallback" = JS(js)
  )
)

Upvotes: 2

Related Questions