【问题标题】:How to change cell colour of Shiny DT table based on formula not cell value?如何根据公式而不是单元格值更改 Shiny DT 表的单元格颜色?
【发布时间】:2020-08-13 22:44:36
【问题描述】:

我想知道是否可以不根据单元格的值而是根据单元格值与用户提供的另一个参考编号之间的差异来更改 DT 表格单元格背景的颜色。因此,如果差异为

以下是使用单元格值作为标准的经典示例,这不是我需要的。 谢谢!

library(shiny)
library(DT)
#> 
#> Attaching package: 'DT'
#> The following objects are masked from 'package:shiny':
#> 
#>     dataTableOutput, renderDataTable

ui <- shinyUI(fluidPage(

    mainPanel(
      DT::dataTableOutput("table")
    )

))

server <- shinyServer(function(input, output) {
  dfr <- data.frame("x"=c(1, 2, 3),
                    "y"=c(10, 12, 14))

  Reference <- 13

  output$table <- DT::renderDataTable(datatable(dfr) %>% formatStyle('y', backgroundColor = styleEqual(c(10, 12, 14), c('gray', 'yellow', 'red'))))

})

shinyApp(ui = ui, server = server)

【问题讨论】:

    标签: shiny dt


    【解决方案1】:

    这是一个可能的解决方案。可能需要一些额外的调整才能完全符合您的要求,但关键功能应该在那里。我使用了您可能感兴趣的 formattable 包。

    library(shiny)
    library(DT)
    library(dplyr)
    library(formattable)
    
    ui <- shinyUI(fluidPage(
    
      mainPanel(
        textInput("input", "put number here"),
        DT::dataTableOutput("table")
      )
    
    ))
    
    server <- shinyServer(function(input, output) {
    
       dfr <- data.frame("x"=c(1, 2, 3),
                         "y"=c(10, 12, 14))
    
      output$table <- DT::renderDataTable(as.datatable(formattable(dfr, list(
        y = formatter("span", 
                      style = y ~ style(
                        color = ifelse(y - as.numeric(input$input) >= 2, "green", ifelse(y - as.numeric(input$input) <= -2, "red", "black"))))
      ))))
    
    })
    
    shinyApp(ui = ui, server = server)
    

    【讨论】:

    • 感谢您的回复,这会起作用,但我希望有一种方法可以更直接地做到这一点,而无需创建额外的列。我的实际数据框可以有很多列,并且创建附加的列是不可取的,因为它们需要被隐藏。我查看了从您提供的链接中隐藏列的示例,但它只是删除了列名和值,而不是实际列本身。
    • 我刚刚更新了答案以删除额外的列。用户输入现在直接用于格式化。这有帮助吗?
    猜你喜欢
    • 2018-09-13
    • 2020-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-15
    • 2014-07-20
    相关资源
    最近更新 更多