user3022875
user3022875

Reputation: 9018

Highlight rows in Shiny DataTable using CallBack or something eles

I was wondering if you could help on something. I have a simple shiny application that renders a dataTable and I would like to highlight the color of the rows based on some criteria.

Here is my code which you can run:

library(shiny)

runApp(list(
  ui = shinyUI(fluidPage(
    sidebarPanel(),
    mainPanel(dataTableOutput("Table")  )
  )),
  server = function(input, output, session) {
    output$Table<- renderDataTable({ 
      Data<-data.frame(RowNumber= c(1,2,3,4,5,6),Type= c("R","E", "R","E","R","G"), YN =c("N","N","Y","N","Y","N"),P = c(500,100,500,900,0,900))
      print(Data[Data$P== 0,])
      Data
    })
  }
))

I have not worked with CSS at all in shiny but I would like to color each row in the data table based on some criteria. The Criteria is:

(1) If "Type" = R AND "YN"= N AND "P" >0 then color the entire row orange 
(2) If "Type" = R AND "YN"= Y AND "P" >0 then color the entire row blue
(3) If "Type" = R AND "YN"= Y AND "P" = 0 then color the entire row yellow

Of course this coloring would have to work with the built in sorting and search functionality etc.

I have seen this solution but couldn't get it to work:

How to change Datatable row background colour based on the condition in a column, Rshiny

The author there mentions the "callback" functionality of the DataTable. Do you know how to use that in this case?

Can you help?

Upvotes: 5

Views: 4493

Answers (1)

NicE
NicE

Reputation: 21425

You need a callback function that is called after the table is created to color the rows.

Here is what you can do:

library(shiny)
        ui <- shinyUI(fluidPage(
                sidebarPanel(),
                mainPanel(dataTableOutput("Table"))
        ))
        server <- function(input, output, session) {
                output$Table<- renderDataTable({ 
                        Data<-data.frame(RowNumber= c(1,2,3,4,5,6),Type= c("R","E", "R","E","R","G"), YN =c("N","N","Y","N","Y","N"),P = c(500,100,500,900,0,900))
                        Data},
                        options = list(rowCallback = I(
                                'function(row, data) {
        if (data[1] == "R" & data[2]=="N" & data[3]>0 )
          $("td", row).css("background", "orange");
        else if (data[1] == "R" & data[2]=="Y" & data[3]>0 )
          $("td", row).css("background", "blue");
        else if (data[1] == "R" & data[2]=="Y" & data[3]==0 )
          $("td", row).css("background", "yellow");
      }'
                        ))
                )
        }

shinyApp(ui = ui, server = server)

If you want more info on the callback you can check this

Upvotes: 4

Related Questions