Изменение цвета для ячеек на столе DT в Shiny - PullRequest
1 голос
/ 12 марта 2020

Я новичок в Shiny / R и пытаюсь изменить цвет фона ячейки (таблицы DT) в зависимости от значения ячейки. Например, значение ячейки в столбце Rec_Color: КРАСНЫЙ, ЗЕЛЕНЫЙ и ЖЕЛТЫЙ. Я хотел бы покрасить ячейку на основе строковых значений. Я пытаюсь использовать функцию "formatStyle", но она не работает для меня. Я получаю эту ошибку:

ОШИБКА. Вы указали столбцы: 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'))

)

1 Ответ

1 голос
/ 20 марта 2020

Несмотря на то, что вы не упомянули, как выглядят данные, я считаю, что решение состоит в том, чтобы изменить следующие строки с

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=.


В вашем коде есть еще одна проблема: функция formatStyle() вызывается на DT::renderDataTable(), но она должно быть DT::datatable(). Поэтому вам также следует изменить код так:

    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...)
        }
        DT::datatable(
          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('Sustainability Color', backgroundColor = styleEqual(c("RED","GREEN","YELLOW"), c('red',"green","yellow")))

    })


Надеюсь, это решит вашу проблему.

Кстати, когда задаете вопросы, пример лучше воспроизводить. Ваш пример невоспроизводим, потому что data.frame неизвестен, а код является лишь частью большого блестящего приложения, которое не может быть запущено напрямую.

...