I am attempting to change the cell color of cells of an R Shiny data table dependent on their value. As an example, I've created the following app:
# ui.R
fluidPage(
# Outputting data table.
DT::dataTableOutput("table")
)
# server.R
library(DT)
data(iris)
function(input, output) {
# Rendering data table.
output$table <- DT::renderDataTable({
head(iris)
},
options = list(dom = "t",
ordering = FALSE))
}
And the following is the generated HTML skeleton and resultant page from the above code:
As an example, lets say that I want all cells containing integers to be colored red. Selectively, I'd like to color only the cells at row 2 column 2 and row 5 column 1 where the values are 3 and 5 respectively. Is this possible in R Shiny?
My current idea for a work around is to set the class of individual cells server-side and color them later with CSS. However, I can't find a way to do this.
This page has a bunch of tips for formatting DT data tables: https://rstudio.github.io/DT/010-style.html
For your specific question, there's the function formatStyle
that allows you to set aesthetics based on specific values in the table:
library(DT)
options(DT.options = list(pageLength = 5))
df = as.data.frame(cbind(matrix(round(rnorm(50), 3), 10), sample(0:1, 10, TRUE)))
# style V6 based on values of V6
datatable(df) %>% formatStyle(
'V6',
backgroundColor = styleEqual(c(0, 1), c('gray', 'yellow'))
)
# style V1 based on values of V6
datatable(df) %>% formatStyle(
'V1', 'V6',
backgroundColor = styleEqual(c(0, 1), c('gray', 'yellow'))
)
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