如果行包含字符串,R Shiny 反应过滤

R Shiny reactive to filter if row contains string

我正在使用 R Shiny 输出 table,但我无法在 renderDataTablereactive 部分进行过滤。我在这个例子中使用 mtcars table,我试图通过 type:

进行过滤
library(shiny)
library(DT)

ui <- fluidPage(
    titlePanel("MTCARS"),
    sidebarLayout(
        sidebarPanel(id="sidebar",
                     textInput("type",
                               label = "Type", 
                               placeholder = "Type"),)
        ,
        mainPanel(
            dataTableOutput("data")
        )
    )
)

server <- function(input, output, session) {
    selected <- reactive({
        if (length(input$type) != 0) {
            mtcars$type %in% input$type
        } else {
            TRUE
        }
    })
    output$data <- renderDataTable(mtcars[selected(),])
}

shinyApp(ui = ui, server = server)

目前,mtcars$type %in% input$type 根据用户输入的 type 过滤 table。但是,我想修改它以便:

  1. 文本不必完全匹配。如果用户键入 Hond.
  2. ,将显示包含 Honda Civic 的行
  3. table 需要从完整的 table 开始。目前它在启动时没有行,尽管有 if/else 语句。

mtcars 没有任何列类型,所以我必须创建一个。我使用 stringr::str_detect 来包含部分匹配的类型。

library(shiny)
library(DT)

data <- mtcars %>%
  rownames_to_column(var = "type")

ui <- fluidPage(
  titlePanel("MTCARS"),
  sidebarLayout(
    sidebarPanel(id="sidebar",
                 textInput("type",
                           label = "Type", 
                           placeholder = "Type"),)
    ,
    mainPanel(
      dataTableOutput("data")
    )
  )
)

server <- function(input, output, session) {
  selected <- reactive({
    if (length(input$type) != 0) {
      stringr::str_detect(data$type, input$type)
    } else {
      TRUE
    }
  })
  output$data <- renderDataTable(data[selected(),])
}

shinyApp(ui = ui, server = server)