Subset a table from textInput with several values

Hello
I'm stuck on one part of an app I'm developing (a simplified version of it is below).
Bascially I have a textInput where the user can write one or several words that will be used to filter a character column of a dataframe using %like%.

My attempt is below but it only returns the matches from the first value if several words are listed in the textInput. For example, in my code below using mtcars, if I input Fiat, Merc it only filters on Fiat. Similarly if I input Merc, Datsun, Mazda it again only filters on Merc.

How do I get it to search using all the values in the textInput?

library(shiny)
library(stringr)
data(mtcars)

ui <- fluidPage(
  titlePanel(""),
  sidebarLayout(
    sidebarPanel(
      textInput(inputId = "textBox",
                label = "Car Search",
                placeholder = "Enter cars here seperated by a comma"),
      actionButton("textSearchButton", "Generate the Table")
    ),
    tableOutput("dtOut")
  )
)

server <- function(input, output) {

  tblFunc <- function(x, car){
    x$make <- rownames(x)
    car <- str_replace(car, ", ", ",")
    car <- unlist(strsplit(car, ","))
    outTbl <- x[x$make %like% car, c(12, 1:4)]
    return(outTbl)
  }

  outTable <- eventReactive(input$textSearchButton, {
    req(input$textBox)
    tblFunc(mtcars, input$textBox)
  })

  output$dtOut <- renderTable({
    outTable()
  })
}

shinyApp(ui, server)

Could you declare your libraries/packages please?

Sorry, just stringr. I edit. Thanks

stringr doesnt define a %like% operator though ?

The code doesn't even really need stringr. You can do roughly the same thing in base R with:

trimws(strsplit(input$cars, ",")[[1]])

Given that this computation is mildly tricky, I'd put it in a reactive, and then show it in an output:

  cars <- reactive(
    trimws(strsplit(input$cars, ",")[[1]])
  )
  output$cars_check <- renderPrint(cars())

For experimentation, I made a somewhat more minimal reprex by pulling out the irrelevant UI code, and
simplifying the server code:

library(shiny)

ui <- fluidPage(
  textInput("cars", "Comma separated cars"),
  textOutput("cars_check"),
  tableOutput("out")
)

server <- function(input, output) {
  cars <- reactive(
    trimws(strsplit(input$cars, ",")[[1]])
  )
  
  output$cars_check <- renderPrint(cars())
  output$out <- renderTable({
    mtcars[rownames(mtcars) %in% cars(), ]
  })
}

shinyApp(ui, server)

I just used %in% since I don't know what package %like% comes from.

%like% is in the DescTools package. It's okay I fouund the %like any% function in the package and all is fixed. Basically like means the same as it is used in SQL. In other words containing, so it is only part of the string. Entering Mazda would bring back all the rows containing the word Mazda in the make field..

This topic was automatically closed 54 days after the last reply. New replies are no longer allowed.