Conditional formatting in DT Data Table R Shiny

前端 未结 1 1706
终归单人心
终归单人心 2021-01-13 03:48

I have a table with 5 cols and 1st column as character and other four as numeric. I am using DT Data Table to display the same in Shiny App. Now, I need to compare each of t

1条回答
  •  一整个雨季
    2021-01-13 03:59

    Here is my solution to your problem:

    library(shinydashboard)
    library(DT)
    library(magrittr)
    
    entity <- c('entity1', 'entity2', 'entity3')
    value1 <- c(21000, 23400, 26800)
    value2 <- c(21234, 23445, 26834)
    value3 <- c(21123, 234789, 26811)
    value4 <- c(27000, 23400, 26811)
    entity.data <- data.frame(entity, value1, value2, value3, value4)
    
    # Create a vector of max values
    max_val <- apply(entity.data[, -1], 1, max)
    
    header <- dashboardHeader()
    sidebar <- dashboardSidebar()
    body <- dashboardBody(DT::dataTableOutput("entity.dataTable"))
    
    shinyApp(
      ui = dashboardPage(header, sidebar, body),
      server = function(input, output) {
        output$entity.dataTable <- renderDataTable({
          DT::datatable(
            entity.data,
            selection = "single",
            filter = 'bottom',
            extensions = c('Buttons', 'ColReorder', 'FixedHeader', 'Scroller'),
            rownames = FALSE,
            options = list(
              dom = 'Bfrtip',
              searching = T,
              pageLength = 25,
              searchHighlight = TRUE,
              colReorder = TRUE,
              fixedHeader = TRUE,
              filter = 'top',
              buttons = c('copy', 'csv', 'excel', 'print'),
              paging    = TRUE,
              deferRender = TRUE,
              scroller = TRUE,
              scrollX = TRUE,
              scrollY = 550
            )
          ) %>% # Style cells with max_val vector
            formatStyle(
            columns = 2:5,
            backgroundColor = styleEqual(levels = max_val, values = rep("yellow", length(max_val)))
          )
        })
      }
    )
    

    So what you need to do is to create a vector of max values. Then use it in the helper function styleEqual() inside formatStyle() as shown in the code above.

    0 讨论(0)
提交回复
热议问题