Search code examples
rshinyshinydashboardshinyappsrshiny

Is it posisble to have two different inputs that can filter my DT table using shiny R?


I have an app that allows me to see the filter the number of cars by using an input.

Here is the code I have.

```{r}

selectInput("input_type","Select Cylinder Size: ", c("All", mtcars$cyl))
selectInput("input_type2", "Select # of Gears: ", c("All", mtcars$gear))

mtcars2 <- reactive({
  if(input$input_type=="All")
    mtcars
  else
    subset(mtcars,cyl == input$input_type)
  })


renderDataTable(
  datatable(mtcars2())
  )  

```

Although I have a second input that can also let me filter by gears, it doesn't work since I can't figure out how to tie it to the reactive function.

Any thoughts?


Solution

  • Something like this [untested code]:

    selectInput("input_type","Select Cylinder Size: ", c("All", mtcars$cyl))
    selectInput("input_type2", "Select # of Gears: ", c("All", mtcars$gear))
    
    mtcars2 <- reactive({
      d <- mtcars
      if(input$input_type !="All")
        d <- subset(d, cyl == input$input_type)
      if(input$input_type2 !="All")
        d <- subset(d, gear == input$input_type2)
      d
      })
    
    
    renderDataTable(
      datatable(mtcars2())
      )  
    

    By the way, you might want to use unique when defining the choices lists for your inputs.