格式表中的动态条件

时间:2017-12-16 23:05:58

标签: r shiny formattable

我正在使用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(mtcars, col_format)

我收到以下错误:

'col_format' of mode 'function' was not found

看似输入$ user_low和输入$ user_high不会被评估,而是被视为格式化程序中的字符串。我试过eval(),eval(parse()),但没有用。

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

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

这将按顺序发生:

  1. 输入元素的值会发生变化。 (input$user_lowinput$user_high
  2. 列格式化条件(col_format)将更新,因为其依赖项已更改。
  3. dataTableOutput已重新呈现,因为它取决于col_format
  4. 示例代码:

    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)
    

    修改:要将格式化程序应用于每个列(根据您的评论),您可以使用{{1>},如动态生成格式化程序部分所示Formattable vignette。下面的代码将格式应用于整个数据集。

    代码:

    lapply