【问题标题】:R Shiny reactive to filter if row contains string如果行包含字符串,R Shiny 反应过滤
【发布时间】:2020-10-28 16:23:53
【问题描述】:

我正在使用 R Shiny 输出一个表格,但我在过滤 reactive 部分中的 renderDataTable 时遇到了问题。我在这个例子中使用了mtcars 表,我试图通过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 过滤表。但是,我想修改它以便:

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

【问题讨论】:

  • 第一点你可以看看grepgrepl函数

标签: r shiny reactive


【解决方案1】:

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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-23
    • 1970-01-01
    • 2018-10-11
    • 2021-10-06
    • 2016-12-08
    • 1970-01-01
    • 2014-05-16
    相关资源
    最近更新 更多