R Shiny - 使用复选框GroupInput过滤data.frame。

问题描述 投票:1回答:1

试图根据勾选的复选框来过滤数据框架中的数据.以下面的例子为例.如果只勾选了 "Apple "框,它将只显示表中以 "Apple "开头的数据.如果只勾选了 "Blue "框,它将只显示表中以 "Blue "开头的数据:

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)
}

如果只选中 "苹果 "框,则只显示表中以 "苹果 "开头的数据;如果只选中 "蓝色 "框,则只显示表中以 "蓝色 "开头的数据;如果只选中 "非苹果或蓝色 "框,则只显示表中以 "苹果 "或 "蓝色 "开头的数据。

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

我知道我需要使用一些通配符来子集数据,但不确定最好的方法。谢谢!

r shiny dt
1个回答
0
投票

一种方法是根据你的复选框设置regex过滤器。一个 if_else 包括声明,以检查 苹果或蓝色的特定情况下。否则将使用 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
      )
    )
  })
}
© www.soinside.com 2019 - 2024. All rights reserved.