How to change the colours of texts in the cells of a data frame based on which text is available

I have written a reproducible code but the colours do not change

library(shiny)
library(DT)

# define the UI
ui <- fluidPage(
  DTOutput("pairwise_table")
)

# define the server
server <- function(input, output) {
  
  # create a sample pairwise comparison dataframe
  pairwise_comp <- data.frame(
    A = c(NA, "EXTREMELY LOW", "MODERATE", "MODERATE"),
    B = c(NA, NA, "EXTREMELY LOW", "EXTREMELY LOW"),
    C = c(NA, NA, NA, "VERY LOW"),
    D = c(NA, NA, NA, NA)
  )
row.names(pairwise_comp)<-c("A","B","C","D")

  # define a function to color the cells based on their values
  color_cells <- function(x) {
    color <- ifelse(is.na(x), "white", 
                    ifelse(x == "EXTREMELY LOW", "red",
                           ifelse(x == "VERY LOW", "orange", "green")))
    c("background-color" = color)
  }
  
  # display the pairwise comparison dataframe as an interactive data table
  output$pairwise_table <- renderDT({
    datatable(pairwise_comp, 
              options = list(
                columnDefs = list(
                  list(targets = "_all", className = "dt-center")
                )
              ), 
              extensions = list(
                list(
                  name = 'rowCallback',
                  js = JS("
                    function(row, data, index) {
                      $('td', row).css(color_cells(data));
                    }
                  ")
                )
              )
    )
  })
  
}

# run the Shiny app
shinyApp(ui, server)

Here is one way to change text color based on cell values using formatStyle() and styleEqual().

output$pairwise_table <- renderDT({
    datatable(pairwise_comp, 
              options = list(
                columnDefs = list(
                  list(targets = "_all", className = "dt-center")
                  )
                )
              ) |>
      formatStyle(1:length(pairwise_comp), 
                  color = styleEqual(c(NA, 'EXTREMELY LOW', 'VERY LOW', 'MODERATE'),
                                     c('white', 'red', 'orange', 'green')
                                     )
                  )
  })

1 Like

@scottyd22 thank you very much! This worked for me.

This topic was automatically closed 54 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.