jqueryrshinydt

How to link a selectInput to a DataTable to update the table based on the selections?


Specifically, I'm using pickerInput (which is similar to selectInput), and a renderDataTable.

Here is what the app looks like (you can see where I'm trying to have the filter update the datatable - if i select 'setosa' the table should update to include just setosa rows):

enter image description here

Here is my minimally reproducible code:

library(shiny)
library(data.table)

results <- iris
results$Species <- as.character(results$Species)

# UI
ui <- fluidPage(
    
    # Application title
    titlePanel(
        h1("Iris Table", align="center")
    ),
    
    fluidRow(
        column(3,
               pickerInput("speciesInput", "Species", choices=unique(results$Species), options = list(`actions-box` = TRUE), selected=NULL, multiple=TRUE)
        ),
        column(9, 
               DT::dataTableOutput('table')))
    
)

# Server
server <- function(input, output) {
    
    
    output$table <- DT::renderDataTable(
        DT::datatable(#filter='top',
            escape = FALSE,
            iris
        ))
    
}

# Run the application 
shinyApp(ui = ui, server = server)

Solution

  • Try this

    library(shiny)
    library(data.table)
    
    results <- iris
    results$Species <- as.character(results$Species)
    
    # UI
    ui <- fluidPage(
      
      # Application title
      titlePanel(
        h1("Iris Table", align="center")
      ),
      
      fluidRow(
        column(3,
               pickerInput("speciesInput", "Species", choices=unique(results$Species), options = list(`actions-box` = TRUE), selected=NULL, multiple=TRUE)
        ),
        column(9, 
               DT::dataTableOutput('table')))
      
    )
    
    # Server
    server <- function(input, output) {
      
      mydata <- reactive({
        if (is.null(input$speciesInput)) {df <- results
        } else df <- results[results$Species %in% input$speciesInput,]
        df
      })
      
      output$table <- DT::renderDataTable(
        datatable(mydata())
        )
      
    }
    
    # Run the application 
    shinyApp(ui = ui, server = server)