Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the cell color of a cell of an R Shiny data table dependent on it's value?

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:

HTML code generated by R Shiny to display the first 6 lines of the iris dataset as a data table

first 6 lines of the iris dataset displayed as a data table in R Shiny

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.

like image 884
michaelmccarthy404 Avatar asked Dec 19 '22 00:12

michaelmccarthy404


1 Answers

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'))
)
like image 191
divibisan Avatar answered Dec 27 '22 03:12

divibisan