Ismail Akrim
Ismail Akrim

Reputation: 51

How to color the whole cells in Shiny renderDataTable() depending on a condition

I'm finding a hard time looking for a way to color cells in a column A using conditions involving another column B.

I'v found out that the package (DT) makes a perfect background in the cell but can't color depending on a formula that involves other columns.

The package (formattable) does the condition that involves the two columns and if I changed the value to

style = ~ style(background = ifelse(S2 >= 50, "lightgreen", "red"))

The background is applied to the value not to the cell itself and that's not what I want.

is there anyway to do that, Thanks

Upvotes: 0

Views: 372

Answers (1)

DS_UNI
DS_UNI

Reputation: 2650

The package tableHTML might be what you're looking for

You can see a lot of examples on what you can do with conditional formatting here: conditional formatting

and you can try this small example with shiny to see what you can do with it:

library(shiny)
library(tableHTML)

ui <- shinyUI(fluidPage(
  titlePanel(title = "tableHTML"),

  sidebarLayout(
    sidebarPanel(h3("Select a Dataset:"),
                 # input
                 selectInput("in_name", "Dataset:", "iris",''),
                 actionButton("in_click", "Submit")),

    mainPanel(h3("Main Panel"), h4("Output"),
              # output
              htmlOutput("out_name"))
    )))

server <- shinyServer(
  function(input, output){
    # # eventReactive
   observeEvent(input$in_click, {df <- eval(parse(text=input$in_name))

    output$out_name <- render_tableHTML({
      # here is the tableHTML part
      tableHTML(df[c(1:5, 51:55, 101:105), 1:4],
                rownames = FALSE,
                headers = rep(c('Length', 'Width'), 2),
                second_headers = list(c(1, 2, 2), c('Species', 'Sepal', 'Petal'))) %>%
        add_css_conditional_column('colour_rank',
                                   colour_rank_theme = 'White-Green',
                                   columns = 1:2,
                                   same_scale = FALSE) %>%
        add_css_conditional_column('colour_rank',
                                   colour_rank_theme = 'White-Blue',
                                   columns = 3:4,
                                   same_scale = FALSE)})
    })
  })

shinyApp(ui, server)

Upvotes: 3

Related Questions