如何使用CSS在Rhandsontable中以特定颜色显示特定列标题?

时间:2019-10-05 17:49:29

标签: html css r shiny rhandsontable

我想使用CSS将特定列的标题颜色更改为特定颜色。例如,有人可以建议如何在标题中将标题“ mpg”,“ hp”和“ gear”的颜色更改为红色,以及如何将“ disp”,“ wt”和“ carb”的颜色更改为蓝色。下面的示例表?

我的问题与该论坛earlier中发布的问题几乎相似。

library(shiny)
library(rhandsontable)

ui <- fluidPage(
  rHandsontableOutput("table1"),
  tags$style(type="text/css", "#table1 th {font-weight:bold;}")
)

server=function(input, output, session) {

  output$table1 <- renderRHandsontable({
    rhandsontable(head(mtcars),rowHeaders=F)
  })
}

shinyApp(ui,server)

1 个答案:

答案 0 :(得分:1)

它需要一些HTML知识。一种方法是将列名从纯文本转换为HTML:

library(shiny)
library(rhandsontable)
library(purrr)
library(glue)
table_headers <- colnames(mtcars)
table_headers_html <- purrr::map_chr(table_headers, function(column){
    if(column %in% c('mpg', 'hp', 'gear')){
        color = "red"
    } else if (column %in% c('disp', 'wt', 'carb')) {
        color = "blue"
    } else {
        color = "black"
    }
    glue::glue("<span style='color:{color}'>{column}</span>")
})
> table_headers_html
 [1] "<span style='color:red'>mpg</span>"    "<span style='color:black'>cyl</span>"  "<span style='color:blue'>disp</span>" 
 [4] "<span style='color:red'>hp</span>"     "<span style='color:black'>drat</span>" "<span style='color:blue'>wt</span>"   
 [7] "<span style='color:black'>qsec</span>" "<span style='color:black'>vs</span>"   "<span style='color:black'>am</span>"  
[10] "<span style='color:red'>gear</span>"   "<span style='color:blue'>carb</span>"

一旦有了HTML中的列标题,就可以在服务器代码中执行以下操作:

server=function(input, output, session) {

    output$table1 <- renderRHandsontable({
        rhandsontable(
            head(mtcars),
            rowHeaders=F,
            colHeaders = table_headers_html
        )
    })
}

enter image description here

相关问题