Change background color

Hi

I would like to change the background color for a column "Motivation" .
The color has to be change if the value is > 50.
I am following this tutorial
https://rstudio.github.io/DT/functions.html

but I cannot find how to accomplish that.

library(shiny)
library(DT)

shinyApp(
  ui <- fluidPage(
    DT::dataTableOutput("data"),
    textOutput('myText')
  ),
  
  server <- function(input, output) {
    
    myValue <- reactiveValues(employee = '')

    
    getData<- function()
    { 
      dt = data.frame(
      Name = c('Dilbert', 'Alice', 'Wally', 'Ashok', 'Dogbert'),
      Motivation = c(62, 73, 3, 99, 4),
      stringsAsFactors = FALSE,
      row.names = 1:5)
    
      colors = ifelse( dat$Motivation >50,'orange','blue')
      colors <- as.data.frame(t(colors)) # transmutation
      datatable(dt) %>% formatStyle(
        'Motivation',
        target = 'row',
        backgroundColor = colors
      )
      
      return (dt)
    }

    df <- reactiveValues(data = getData())
    
    output$data <- DT::renderDataTable(
      df$data, server = FALSE, escape = FALSE, selection = 'none'
    )
  
  }
)

In your example you create dt then modifies the style with formatStyle but your getData function return dt so your modifications are not taken into account. You need to assign the creation of datatabe + formatStyle then return this element which is no more a table but a DT::datatable. You'll then need some modification in renderDataTable

Here is a working example,simpler because everything is created in renderDataTable

library(shiny)
library(DT)

shinyApp(
  ui <- fluidPage(
    DT::dataTableOutput("data"),
    textOutput('myText')
  ),
  
  server <- function(input, output) {
    
    myValue <- reactiveValues(employee = '')
    
    
    output$data <- DT::renderDataTable({
      dt = data.frame(
        Name = c('Dilbert', 'Alice', 'Wally', 'Ashok', 'Dogbert'),
        Motivation = c(62, 73, 3, 99, 4),
        stringsAsFactors = FALSE,
        row.names = 1:5)
      
      datatable(dt, escape = FALSE, selection = 'none') %>% 
        formatStyle(
          'Motivation',
          target = 'row',
          backgroundColor = styleInterval(50, c('orange', 'blue'))
        )
    }
    )
    
  }
)
2 Likes

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