4

I am trying to format the background color of table cells in an R Shiny app based on the content of the cell. The content is either TRUE or FALSE and was assigned using a boolean function. Is styleEqual() not the right way to format the cells? The following will run, but my cells remain uncolored.

output$myTable <-
      DT::renderDataTable({
        result<-custom_function()
        result<-
        datatable(result)%>% formatStyle(
          names(result),
          backgroundColor = styleEqual(c(TRUE, FALSE), c('green', 'red'))
        )
        return(res)
      })
1
  • Reproducible example will be helpful. Try define a specific column where T and F can be test to assign color.
    – A. Suliman
    May 5, 2018 at 5:33

1 Answer 1

4

styleEqual is the way to go, but you need to use numeric (1, 0) values instead of logical (TRUE, FALSE).

Here's an example:

library(shiny)
library(DT)
library(magrittr)

iris2 <- iris
iris2$logical <- ifelse(iris$Sepal.Length > 5, TRUE, FALSE)

ui <- fluidPage(
  DT::dataTableOutput("tbl")  
)

server <- function(input, output, session) {
  output$tbl <- DT::renderDataTable( {
    datatable(iris2) %>% formatStyle(
      "logical",
      target = 'row',
      backgroundColor = styleEqual(c(1, 0), c('green', 'red'))
    )
  })
}

shinyApp(ui, server)

Example

1
  • Thank you! Got it to work. You can also do an if_else statement in your dplyr mutate on the TRUE/FALSE column and set it to anything you want, like a "yes", "no" or "match", "non-match". That's what I ended up doing.
    – zelda26
    May 10, 2018 at 17:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.