【问题标题】:Dynamic conditions in formattable格式化表中的动态条件
【发布时间】:2017-12-16 23:05:57
【问题描述】:

我正在使用 formattable 在闪亮应用程序的表格中实现一些条件颜色格式。例如,假设我想将值低于 2 的单元格着色为绿色,高于 5 的单元格为红色,介于 2 和 5 之间的单元格为橙色。我会这样写我的格式化函数:

formatter(
  "span", 
  style = x ~ style(
  color = 'white',
  'background-color' =  
    ifelse(x > 5, "red",
      ifelse(x > 2 & x <= 5, "orange",
        "green"))))

但是,我真正想要做的是让用户能够更改这些颜色阈值,即 2 和 5。

假设 user_low 和 user_high 是由用户定义的:

col_format <- 
  formatter(
      "span", 
      style = x ~ style(
      color = 'white',
      'background-color' =  
        ifelse(x > input$user_high, "red",
          ifelse(x > input$user_low & x <= input$user_high, "orange",
            "green"))))

如果我现在尝试将此格式化程序提供给我闪亮的应用程序中的 formattable:

formattable(mtcars, col_format)

我收到以下错误:

'col_format' of mode 'function' was not found

似乎 input$user_low 和 input$user_high 没有被评估,而是在格式化程序中被视为字符串。我试过 eval(), eval(parse()),没有用。

有什么想法吗?

【问题讨论】:

  • 不确定formattable 但使用tableHTML 真的很容易。检查here。它也适用于闪亮。
  • 很好@LyzanderR。我还没有看到tableHTML,绝对是一个很好的备份。不过 Formattable 看起来更好一些,如果可能的话,我想在那个框架中做到这一点

标签: r shiny formattable


【解决方案1】:

您的代码几乎可以正常运行,但如果您想在表达式中使用 input$user_high 等输入元素,则必须使用 reactive

这将按顺序发生:

  1. 输入元素的值发生变化。 (input$user_lowinput$user_high
  2. 列格式条件 (col_format) 将更新,因为它的依赖关系发生了变化。
  3. dataTableOutput 被重新渲染,因为它依赖于 col_format

示例代码:

library(shiny)
library(formattable)
library(DT)

ui <- fluidPage(
  sidebarLayout(
    sidebarPanel(
      numericInput("user_low", "User low", value = 2, min = 1, max = 5),
      numericInput("user_high", "User high", value = 8, min = 6, max = 10)
    ),

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

server <- function(input, output) {
  output$table <- DT::renderDataTable( {
    as.datatable(formattable(mtcars, list(
      cyl = col_format()
    )))
  })

  col_format <- reactive( {
    formatter(
      "span",
      style = x ~ style(
        color = 'white',
        'background-color' =
          ifelse(x > input$user_high, "red",
                 ifelse(x > input$user_low & x <= input$user_high, "orange",
                        "green"))))
  })

}

shinyApp(ui, server)

编辑:要将格式化程序应用于每一列(根据您的评论),您可以使用lapply,如@中的动态生成格式化程序部分所示987654321@。下面的代码将格式应用于整个数据集。

代码:

output$table <- DT::renderDataTable( {
  as.datatable(formattable(mtcars, lapply(1:ncol(mtcars), function(col) {
    area(row = 1:nrow(mtcars), col) ~ col_format() 
  })))
})

【讨论】:

  • 啊!谢谢你@GyD。实际上,我确实尝试将格式化程序放在反应式中并且它不起作用,但我现在意识到这是因为我试图将格式化程序应用于每一列(不仅仅是cyl,如您的回答)。我可能应该提到这一点。我会将问题标记为已回答,但如果您对如何将格式化程序应用于 mtcar 的每一列有任何想法,我们将不胜感激!
  • @quantumcatz 您可以为此使用lapply,因为您需要向formattable 提供一个列表。有关详细信息,请参阅我编辑的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-03-08
  • 1970-01-01
  • 2014-03-30
  • 2016-03-15
  • 2012-10-19
  • 2015-10-23
  • 2021-11-24
相关资源
最近更新 更多