Search code examples
rfiltershinydashboard

R shinydashboard - Filter a datable based on the input of a user


The question is as follows:

"How do I filter a datatable based on the input of a user in my shinydashboard?"

Have a look at the reproducible code below. Within the 'user' tab I allow a user to filter the standard iris dataset based on the type of species (for example setosa or versicolor). I am however unable to show the filtered datable.

To solve my problem, I have looked at multiple posts:

However, without any success. I was hoping that one of you could help me.

This is my first post on stackoverflow. I hope that it meets the rules by stackoverflow. If not, please let me know what I need to alter.

librarian::shelf(datasets, dplyr, DT, shiny, shinydashboard)

data("iris")
iris

ui <- dashboardPage(
    skin = "red", 
    dashboardHeader(title = "Shiny dashboard", titleWidth = 300),
    dashboardSidebar(
        width = 300,
        sidebarMenu(
            menuItem("1. Administrator", tabName = "administrator", icon = icon("tools")),
            menuItem("2. User", tabName = "user", icon = icon("user"))
        )
    ),
    dashboardBody(
        tabItems(
            tabItem("administrator",
                    div(p("In development"))
            ),
            tabItem("user",
                    selectInput("species", "Select a species", iris$Species),
                    dataTableOutput("irisspecies"),
                    downloadButton(outputId = "download", label = "Download .PDF"))
        )
    )
)

server <- function(input, output) {
}

shinyApp(ui, server)


Solution

  • I actually found a very easy solution.

    With respect to the server side, just add:

    server <- function(input, output) {
        output$select_species <- renderDataTable({
            iris %>% 
                filter(Species == input$species)
        })
    }
    

    Answering my own question defeats the purpose of stackoverflow. However, I hope that the question will still help others.