R Shiny reactive to filter if row contains string

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)

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top