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 the four cols for each row and color code the row cell which has maximum value. Looking for ways to do the same. Had a look on this link as well StylingCells but all the cols are numeric here.
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)
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
)
)
})
}
)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With