Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Highlight rows in Shiny DataTable using CallBack or something eles

Tags:

css

r

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?

like image 702
user3022875 Avatar asked Sep 29 '22 20:09

user3022875


1 Answers

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

like image 97
NicE Avatar answered Oct 06 '22 18:10

NicE