Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add text colour to a specific column name (header) in DT Shiny datatable

Tags:

dt

shiny

I am fairly new to DT in Shiny and would like to add text colour to specific columns in a table, I can do this using formatStyle as per the below example code chunk. However, I would also like to add the same text colour to the corresponding column name (header), is there an easy way to do this?

library(shiny)
library(DT)

ui = fluidPage(DT::dataTableOutput('fDataTable'))

server = function(input, output) {
  output$fDataTable = DT::renderDataTable({
    DT::datatable(iris) %>%
      formatStyle(columns = 1, color = "red") %>%
      formatStyle(columns = 3, color = "blue")
  })
}  

app = list(ui = ui, server = server)
runApp(app)

Any help would be greatly appreciated.

like image 976
lmsimp Avatar asked Jan 07 '23 18:01

lmsimp


1 Answers

You can do this by adding CSS to the colnames of the table you are rendering (you also need to set escape to FALSE or the html will be escaped).

Here's an example:

library(shiny)
library(DT)

ui = fluidPage(DT::dataTableOutput('fDataTable'))

server = function(input, output) {
  output$fDataTable = DT::renderDataTable({
    iris_coloured <- iris
    colnames(iris_coloured)[c(1,3)] <- paste0('<span style="color:',c("red","blue"),'">',colnames(iris)[c(1,3)],'</span>')
    DT::datatable(iris_coloured,escape=F) %>%
      formatStyle(columns = 1, color = "red") %>%
      formatStyle(columns = 3, color = "blue")
  })
}  

app = list(ui = ui, server = server)
runApp(app)
like image 85
NicE Avatar answered Feb 06 '23 16:02

NicE