bltSandwich21
bltSandwich21

Reputation: 432

R Shiny reactive to filter if row contains string

I am using R Shiny to output a table, but I am having trouble filtering in the reactive part for the renderDataTable. I am using the mtcars table in this example, and I am trying to filter by 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)

Currently, mtcars$type %in% input$type filters the table based on what the user inputs as the type. However, I want to modify this so that:

  1. The text does not have to match exactly. Rows that contain Honda Civic will show up if the user types Hond.
  2. The table needs to start out with the full table. Currently it has no row when it is starting despite having the if/else statement.

Upvotes: 1

Views: 1017

Answers (1)

Jakub.Novotny
Jakub.Novotny

Reputation: 3047

mtcars does not have any column type so I had to create one. I used stringr::str_detect to include also partially matched types.

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)

Upvotes: 2

Related Questions