【问题标题】:R Shiny - filter data.frame with checkboxGroupInputR Shiny - 使用 checkboxGroupInput 过滤 data.frame
【发布时间】:2020-08-14 21:27:34
【问题描述】:

尝试根据选中的复选框过滤数据框中的数据。 举个例子:

if (interactive()) {
  library(DT)

  Dish <- c("Apple Pie", "Apple Cake", "Blueberry Pie", "Lemon", "Carrot", "Chocolate")
  DishNum <- c("123", "456", "789", "12", "34", "56")
  data <- data.frame(Dish, DishNum)

  ui <- fluidPage(
    checkboxGroupInput(inputId = "chkDish",
                       label = "",
                       inline = TRUE,
                       choices = c("Apple", "Blue", "Not Apple or Blue"),
                       selected = c("Apple", "Blue", "Not Apple or Blue")
    ),
    DT::dataTableOutput(outputId = "DT_Dish")
  )

  server <- function(input, output, session) {
    output$DT_Dish <- DT::renderDataTable({
      DT::datatable(
        data,
        rownames = FALSE,
        options = list(
          dom = 't',
          searchHighlight = TRUE,
          pageLength = 100,
          scrollX = TRUE
        )
      )
    })
  }
  shinyApp(ui, server)
}

如果仅选中“Apple”框,则只会显示以“Apple”开头的表格中的数据。 如果仅选中“蓝色”框,则只会显示表格中以“蓝色”开头的数据。 如果只勾选“Not Apple or Blue”复选框,它只会显示表格中不以“Apple”或“Blue”开头的数据。

如果选中任何按钮组合,它将适当地过滤/显示数据。

我知道我需要使用一些通配符来对数据进行子集化,但不确定解决此问题的最佳方法。谢谢!

【问题讨论】:

    标签: r shiny dt


    【解决方案1】:

    解决此问题的一种方法是根据您的复选框设置正则表达式过滤器。包含if_else 语句以检查 not apple 或 blue 特定情况。否则将在正则表达式中使用input$chkDisk 字符值。使用或 (|) 搜索所有过滤器。看看这是否提供了所需的行为。

    library(dplyr)
    
    server <- function(input, output, session) {       
      filtered_data <- reactive({
        req(input$chkDish)
        filters <- if_else(input$chkDish == "Not Apple or Blue", "(?!Apple)(?!Blue)", paste0("(", input$chkDish, ")"))
        filter(data, grepl(paste0("^(", paste0(filters, collapse="|"), ")"), Dish, perl = TRUE))
      })
    
      output$DT_Dish <- DT::renderDataTable({
        DT::datatable(
          filtered_data(),
          rownames = FALSE,
          options = list(
            dom = 't',
            searchHighlight = TRUE,
            pageLength = 100,
            scrollX = TRUE
          )
        )
      })
    }
    

    【讨论】:

    • 绝对精彩。这正是我想要做的。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-29
    • 1970-01-01
    • 2018-10-16
    • 2017-05-03
    • 2019-05-26
    • 2017-09-17
    • 1970-01-01
    相关资源
    最近更新 更多