将文本颜色添加到 DT Shiny 数据表中的特定列名称 (header)

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

我对 Shiny 中的 DT 还很陌生,想将文本颜色添加到 table 中的特定列,我可以按照下面的示例代码块使用 formatStyle 来做到这一点。不过,我也想在相应的列名(header)中添加相同的文本颜色,有没有简单的方法可以做到这一点?

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)

如有任何帮助,我们将不胜感激。

您可以通过将 CSS 添加到您正在渲染的 table 的 colnames 来实现(您还需要将 escape 设置为 FALSE否则 html 将被转义)。

这是一个例子:

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)