如何过滤和设置数据样式 table

How to filter and style a data table

我正在制作一个闪亮的应用程序,它允许用户从下拉列表中选择一个数据框,然后将其格式化为 DT 数据 table。我希望用户能够按列值过滤数据,并且我希望某些行具有红色文本。这是应用程序的代码:

global.R:

df1 <- data.frame(Name = c("a", "b", "c"),
                  Parameter = c("pH", "pH", "pH"),
                  Amount = c(7, 7.5, 6.8),
                  Violation = c("No", "No", "Yes"))

df2 <- data.frame(Name = c("d", "e", "f"),
                  Parameter = c("pH", "pH", "pH"),
                  Amount = c(6.7, 7.2, 7.3),
                  Violation = c("Yes", "No", "No"))

ui.R

shinyUI(fluidPage(

    titlePanel("Title"),

    fluidRow(
        selectInput(inputId = "df_test",
                    label = "Select DF",
                    choices = c("DF 1" = "df1", 
                                "DF 2" = "df2"), 
                    selected = "DF 1", 
                    width = "50%"),
    
        
        DT::dataTableOutput("test_table")
    )
))

server.R:

shinyServer(function(input, output) {
    
    output$test_table <- DT::renderDataTable({
        get(input$df_test)
    })

})

我想在数据顶部添加过滤条 table 并将违规列中的“是”值设为红色。在常规 R 脚本中,我会这样做。

datatable(df1, filter = "top", 
                                options = list(pageLength = 25, autoWidth = TRUE)) %>% 
  formatStyle("Violation", valueColumns = "Violation", color = styleEqual("Yes", 'red')) 
 

我如何在 Shiny 应用程序中实现这一点,以便从 selectInput 中选择的数据框格式如下?

我们可以将 datatable 代码包裹在 get(input$df_test)

周围
library(shiny)
library(dplyr)

df1 <- data.frame(Name = c("a", "b", "c"),
                  Parameter = c("pH", "pH", "pH"),
                  Amount = c(7, 7.5, 6.8),
                  Violation = c("No", "No", "Yes"))

df2 <- data.frame(Name = c("d", "e", "f"),
                  Parameter = c("pH", "pH", "pH"),
                  Amount = c(6.7, 7.2, 7.3),
                  Violation = c("Yes", "No", "No"))


ui = fluidPage(
  
  titlePanel("Title"),
  
  fluidRow(
    selectInput(inputId = "df_test",
                label = "Select DF",
                choices = c("DF 1" = "df1", 
                            "DF 2" = "df2"), 
                selected = "DF 1", 
                width = "50%"),
    
    
    DT::dataTableOutput("test_table")
  )
)


server <- function(input, output) {
  
  output$test_table <- DT::renderDataTable({
    
    
    DT::datatable(get(input$df_test), filter = "top", 
              options = list(pageLength = 25, autoWidth = TRUE)) %>% 
      DT::formatStyle("Violation", valueColumns = "Violation", color = DT::styleEqual("Yes", 'red')) 
  })
}
shinyApp(ui, server)

-输出