请获得帮助,我对更改DT表上单元格的颜色感到困惑-闪亮

问题描述 投票:0回答:1

我不熟悉Shiny / r,并尝试根据Cell的值更改其背景颜色(DT表)。例如对于Rec_Color列上的单元格值是红色,绿色和黄色。我想为字符串值上的单元格上色。我尝试使用“ formatStyle”功能,但对我不起作用。我收到此错误:(ERROR。您指定了列:Rec_Color,但是数据的列名是)。我被困住了..任何帮助将不胜感激。这是我的表(和过滤器输入)的代码:

output$spTable <- DT::renderDataTable ({data <- TrustSp_Data  # Code for the trust species table and the selecInputs

    if (input$Tax != "All") {
        data <- data[data$Taxon == input$Tax,] # selectInput for Taxa
    }

    if (input$Rcolor != "All") {
        data <- data[data$Rec_Color == input$Rcolor,] # selectInput for Recovery color
    }

    if (input$Cstat != "All") {
        data <- data[data$Status == input$Cstat,] # selectInput for conservation status ( T&E, At-risk, etc...)
    }

    if (input$Rtime != "All") {
        data <- data[data$Rec_Time == input$Rtime,] # selectInput for Recovery Timeline (1:6)
    }

    if (input$Autho != "All") {
        data <- data[data$Authority == input$Autho,] # selectInput for federal Authority ( ESA, MBTA, etc...)
    }

    data
}, rownames=FALSE, #remove first column row numbers
   extensions = c('ColReorder','Responsive',"FixedHeader"), # add "extensions = "Responsive" to add large number of columns

 # caption = "Table 1: This is a sample caption for the table.", # Add caption at the top

   caption = htmltools::tags$caption( # Add caption at the bottom of the table
                                     style = 'caption-side: bottom; text-align: center;',
                                     'Dataset:', htmltools::strong("Version 03-January 10, 2019")),


   colnames = c("ID"=1,"Species Name"=3,"Scientific Name"=4, "Sustainability Color"=7, "Sustainability Timeline"=8, "ITIS ID"=9), # Change columns names


options = list(
     fixedHeader = TRUE,
     scrolly = TRUE,
     colReorder = TRUE,
     columnDefs = list(list(className = 'dt-center', targets = c(0,1,7))), # columns aligment to center
     language = list(sSearch = "Search Table:"),
initComplete = JS(
  "function(settings, json) {",
  "$(this.api().table().header()).css({'background-color': '#22415e', 'color': '#fff'});",
  "}")

  ) %>% formatStyle(columns = "Rec_Color",
            backgroundColor = styleEqual(
           c("GREEN", "RED", "YELLOW"), c('green', "red", 'yellow'))

)
datatable shiny shinydashboard dt
1个回答
0
投票

尽管您没有提到数据的样子,但我相信解决方案是更改以下几行的内容

formatStyle(columns = "Rec_Color",
            backgroundColor = styleEqual(
           c("GREEN", "RED", "YELLOW"), c('green', "red", 'yellow'))

formatStyle(columns = "Sustainability Color",
            backgroundColor = styleEqual(
           c("GREEN", "RED", "YELLOW"), c('green', "red", 'yellow'))

原因是您通过指定colnames=选项更改了列名。

我希望这能解决您的问题。

BTW,当问问题时,该示例最好是可重现的。您的示例不可复制,因为data.frame是未知的,并且代码仅是大型闪亮应用程序的一部分,该应用程序无法直接运行。

© www.soinside.com 2019 - 2024. All rights reserved.