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

I have a real-time log file running, that listens to the database and renders a datatable of the most recent updates on top. However after spending sometime on it im stuck on how to change the background colour with an if statement, as I am not familiar with Javascript.

1) a) How can I change the background colour to green whenever my "Test" Column is "Pass". b) To red when its "Aggr" c) and grey when its "Bad". I have looked at R shiny colour dataframe and How to have conditional formatting of data frames in R Shiny? and I can modify the scipt to something like so

script <- "$('tbody tr td:nth-child(1)').each(function() {

          var cellValue = $(this).text();

          if (cellValue == "Pass") {
            $(this).parent().css('background-color', 'green');
          }
          else if (cellValue == "Aggr") {
            $(this).parent().css('background-color', 'red');
          }
          else if (cellValue == "Bad") {
            $(this).parent().css('background-color', 'grey');
          }

        })"

But this only does it once. I also looked into this r shiny: highlight some cells however the library gives me an error Error: package ‘ReporteRsjars’ could not be loaded and I cannot install that package to go this way either.

Possible solutions:

i) I can change my Log table into the textoutput and change colours there using shinyBS library or some other tools, theres a great example here of the ChatRoom in Rshiny gallery.

ii) I can go with googlevis package, however I would be facing issues with reprinting the table every iteration (same as its done here, however its not as 'noticeable').

2) How can I render my datatable output only when new point is added to it. E.g. I dont want to reprint the datatable again if nothing changed?

Thank you in advance...

My sample code is below

rm(list = ls())
library(shiny)
options(digits.secs=3) 

test_table <- cbind(rep(as.character(Sys.time()),2),rep('a',2),rep('b',2),rep('b',2),rep('c',2),rep('c',2),rep('d',2),rep('d',2),rep('e',2),rep('e',2))
colnames(test_table) <- c("Time","Test","T3","T4","T5","T6","T7","T8","T9","T10")

ui =navbarPage(inverse=TRUE,title = "Real-Time Logs",
               tabPanel("Logs",icon = icon("bell"),
                        mainPanel(htmlOutput("logs"))),
               tabPanel("Logs 2",icon = icon("bell")),
               tabPanel("Logs 3",icon = icon("bell")),
               tags$head(tags$style("#logs {height:70vh;width:1000px;!important;text-align:center;font-size:12px;}")),
               tags$style(type="text/css", "#logs td:nth-child(1) {height:20px;font-size:12px;text-align:center}"),
               tags$style(type="text/css", "#logs td:nth-child(2) {width:70px;height:20px;font-size:12px;text-align:center}"),
               tags$style(type="text/css", "#logs td:nth-child(3) {width:70px;height:20px;font-size:12px;text-align:center}"),
               tags$style(type="text/css", "#logs td:nth-child(4) {width:70px;height:20px;font-size:12px;text-align:center}"),
               tags$style(type="text/css", "#logs td:nth-child(5) {width:70px;height:20px;font-size:12px;text-align:center}"),
               tags$style(type="text/css", "#logs td:nth-child(6) {width:70px;height:20px;font-size:12px;text-align:center}"),
               tags$style(type="text/css", "#logs td:nth-child(7) {width:70px;height:20px;font-size:12px;text-align:center}"),
               tags$style(type="text/css", "#logs td:nth-child(8) {width:70px;height:20px;font-size:12px;text-align:center}"),
               tags$style(type="text/css", "#logs td:nth-child(9) {width:70px;height:20px;font-size:12px;text-align:center}"),
               tags$style(type="text/css", "#logs td:nth-child(10) {width:70px;height:20px;font-size:12px;text-align:center}")
)
server <- (function(input, output, session) {
  autoInvalidate1 <- reactiveTimer(1000,session)

  my_test_table <- reactive({
    autoInvalidate1()
    other_data <- rbind(c(as.character(Sys.time()),(sample(c("Pass","Aggr","Bad"))[1]),round(c(rnorm(1),rnorm(1),rnorm(1),rnorm(1),rnorm(1),rnorm(1),rnorm(1),rnorm(1)),2)),  
                        (c(as.character(Sys.time()),(sample(c("Pass","Aggr","Bad"))[1]),round(c(rnorm(1),rnorm(1),rnorm(1),rnorm(1),rnorm(1),rnorm(1),rnorm(1),rnorm(1)),2))))
    test_table <<- rbind(apply(other_data, 2, rev),test_table)
    as.data.frame(test_table) 
  })
  output$logs <- renderTable({my_test_table()},include.rownames=FALSE)

})

runApp(list(ui = ui, server = server))

Answers:

Answer

You can add a custom message which you can call using the session$onFlushed method. To keep the example succinct I have removed formatting and extra tabs. First the script and call to shiny. Notuce we equate to " Pass " rather then "Pass" etc. as xtable seems to add extra spacing:

library(shiny)
options(digits.secs=3) 
script <- "
els = $('#logs tbody tr td:nth-child(2)');
console.log(els.length);
els.each(function() {
          var cellValue = $(this).text();
          if (cellValue == \" Pass \") {
            $(this).parent().css('background-color', 'green');
          }
          else if (cellValue == \" Aggr \") {
            $(this).parent().css('background-color', 'red');
          }
          else if (cellValue == \" Bad \") {
            $(this).parent().css('background-color', 'grey');
          }
        });"
test_table <- cbind(rep(as.character(Sys.time()),2),rep('a',2),rep('b',2),rep('b',2),rep('c',2),rep('c',2),rep('d',2),rep('d',2),rep('e',2),rep('e',2))
colnames(test_table) <- c("Time","Test","T3","T4","T5","T6","T7","T8","T9","T10")

and the app

ui =navbarPage(inverse=TRUE,title = "Real-Time Logs",
               tabPanel("Logs",icon = icon("bell"),
                        mainPanel(
                          htmlOutput("logs"))
                        , tags$script(sprintf('
                          Shiny.addCustomMessageHandler("myCallback",
                            function(message) {
                                 %s
                            });
                          ', script)
                        )
                        )
)
server <- (function(input, output, session) {
  autoInvalidate1 <- reactiveTimer(3000,session)
  my_test_table <- reactive({
    autoInvalidate1()
    other_data <- rbind(c(as.character(Sys.time()),(sample(c("Pass","Aggr","Bad"))[1]),round(c(rnorm(1),rnorm(1),rnorm(1),rnorm(1),rnorm(1),rnorm(1),rnorm(1),rnorm(1)),2)),  
                        (c(as.character(Sys.time()),(sample(c("Pass","Aggr","Bad"))[1]),round(c(rnorm(1),rnorm(1),rnorm(1),rnorm(1),rnorm(1),rnorm(1),rnorm(1),rnorm(1)),2))))
    test_table <<- rbind(apply(other_data, 2, rev),test_table)
    session$onFlushed(function(){
      session$sendCustomMessage(type = "myCallback", "some message")
    })
    as.data.frame(test_table) 
  })
  output$logs <- renderTable({my_test_table()},include.rownames=FALSE)
})

runApp(list(ui = ui, server = server))

When you add back in the formatting and extra tabs it looks like:

enter image description here

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.