DT数据表R Shiny中的条件格式

时间:2017-08-29 10:26:26

标签: r shiny dt

我有一个包含5个cols和第1列作为字符的表,其他4个作为数字。我正在使用DT数据表在Shiny App中显示相同的内容。现在,我需要比较每行的四个cols中的每一个,并且颜色代码具有最大值的行单元格。寻找方法来做同样的事情。看看这个链接StylingCells,但所有的cols都是数字。

代码

entity <- c('entity1', 'entity2', 'entity3')
value1 <- c(21000, 23400, 26800)
value2 <- c(21234, 23445, 26834)
value3 <- c(21123, 234789, 26811)
value4 <- c(27000, 23400, 26811)
entity.data <- data.frame(entity, value1, value2, value3, value4)

header <- dashboardHeader()
sidebar <- dashboardSidebar()
body <- dashboardBody(DT::dataTableOutput("entity.dataTable"))

shinyApp(
  ui = dashboardPage(header, sidebar, body),
  server = function(input, output) {
    output$entity.dataTable <- renderDataTable({
      DT::datatable(
        entity.data,
        selection = "single",
        filter = 'bottom',

        extensions = c('Buttons', 'ColReorder', 'FixedHeader', 'Scroller'),
        rownames = FALSE,
        options = list(
          dom = 'Bfrtip',
          searching = T,
          pageLength = 25,
          searchHighlight = TRUE,
          colReorder = TRUE,
          fixedHeader = TRUE,
          filter = 'top',
          buttons = c('copy', 'csv', 'excel', 'print'),
          paging    = TRUE,
          deferRender = TRUE,
          scroller = TRUE,
          scrollX = TRUE,
          scrollY = 550

        )

      )

    })
  }
)

1 个答案:

答案 0 :(得分:1)

以下是我解决问题的方法:

library(shinydashboard)
library(DT)
library(magrittr)

entity <- c('entity1', 'entity2', 'entity3')
value1 <- c(21000, 23400, 26800)
value2 <- c(21234, 23445, 26834)
value3 <- c(21123, 234789, 26811)
value4 <- c(27000, 23400, 26811)
entity.data <- data.frame(entity, value1, value2, value3, value4)

# Create a vector of max values
max_val <- apply(entity.data[, -1], 1, max)

header <- dashboardHeader()
sidebar <- dashboardSidebar()
body <- dashboardBody(DT::dataTableOutput("entity.dataTable"))

shinyApp(
  ui = dashboardPage(header, sidebar, body),
  server = function(input, output) {
    output$entity.dataTable <- renderDataTable({
      DT::datatable(
        entity.data,
        selection = "single",
        filter = 'bottom',
        extensions = c('Buttons', 'ColReorder', 'FixedHeader', 'Scroller'),
        rownames = FALSE,
        options = list(
          dom = 'Bfrtip',
          searching = T,
          pageLength = 25,
          searchHighlight = TRUE,
          colReorder = TRUE,
          fixedHeader = TRUE,
          filter = 'top',
          buttons = c('copy', 'csv', 'excel', 'print'),
          paging    = TRUE,
          deferRender = TRUE,
          scroller = TRUE,
          scrollX = TRUE,
          scrollY = 550
        )
      ) %>% # Style cells with max_val vector
        formatStyle(
        columns = 2:5,
        backgroundColor = styleEqual(levels = max_val, values = rep("yellow", length(max_val)))
      )
    })
  }
)

所以你需要做的是创建一个最大值的向量。然后在styleEqual()内的帮助函数formatStyle()中使用它,如上面的代码所示。