3

I have a very simple issue. I am trying to conditionally color certain cells of a shiny renderTable. For some reason the method below is coloring one cell to the right and pushing the cells in the row over one column as well:

test <- data.frame(test1 = c(1:3), test2 = c(4:6))
test[test$test1 == 1, "test1"] <- '<td style="background-color:red">'

library(shiny)

ui <- shinyUI(fluidPage(
   tableOutput("tt")
   )
)

server <- shinyServer(function(input, output) {

   output$tt <- renderTable({
     test
   }, sanitize.text.function = function(x) x)
})

shinyApp(ui = ui, server = server)

Is this a bug? When I inspected the HTML output I saw it is leaving a blank <td> </td> cell and creating a new <td style="background-color:red">. I Also tried:

test[test$test1 == 1, "test1"] <- '<td bgcolor="#FF0000">1</td>'

This other styling works:

test[test$test1 == 1, "test1"] <- "<strong>1</strong>"

I am trying to avoid more complex solutions such as:

R shiny color dataframe

Is this too simple to work? Thank you so much.

Community
  • 1
  • 1
Tunn
  • 1,506
  • 16
  • 25
  • You want to use only renderTable? or may be HtmlTable or DT ? – Batanichek Sep 26 '16 at 10:31
  • @Batanichek For simplicity sake, I'd like to stick with renderTable. If it can't be done I can use other functions and packages (looking like DT is the way to go for tables so I should probably start learning it anyway). – Tunn Sep 26 '16 at 13:03

1 Answers1

4

If you want to do it only using renerTable you can try to add div into td

Example

( but you may need some css manipulation to achive same text position)

test <- data.frame(test1 = c(1:3), test2 = c(4:6))
test[test$test1 == 1, "test1"] <- '<div style="width: 100%; height: 100%; z-index: 0; background-color: green; position:absolute; top: 0; left: 0; padding:5px;">
<span>1</span></div>'

library(shiny)

ui <- shinyUI(fluidPage(
  tableOutput("tt"),
  tags$head(tags$style("#tt td{
                       position:relative;
                       };
                       
                       "))
  )
  )

server <- shinyServer(function(input, output) {
  
  output$tt <- renderTable({
    test
  }, sanitize.text.function = function(x) x)
})

shinyApp(ui = ui, server = server) 

In DT you can do it in such way :

test <- data.frame(test1 = c(1:3), test2 = c(4:6))

library(shiny)
library(DT)

ui <- shinyUI(fluidPage(
  DT::dataTableOutput("tt")
)
)

server <- shinyServer(function(input, output) {
  
  output$tt <- DT::renderDataTable({
    datatable(test)%>%formatStyle("test1",backgroundColor=styleEqual(1, "red"))
  })
})

shinyApp(ui = ui, server = server)

As you can see in DT version you not need any css styles etc

Community
  • 1
  • 1
Batanichek
  • 7,761
  • 31
  • 49