Search code examples
filtershinyflexdashboardselectinput

Filtering from selected input in R shiny


I keep getting errors when trying to filter a data base according to a selected input. I made this really simple example based on the iris dataset to show you guys my problem:


    ```{r}
    library(flexdashboard)
    library(tidyverse)
    ```
    
    Sidebar {.sidebar}
    =====================================
    
    ```{r}
    
    fluidRow(
      column(7,
             selectInput("Species", "Choose a species",
                         choices = c("setosa", "versicolor", "virginica"))))
    
    mydata <- reactive({
    iris %>% filter(Species == input$Species)
    })
    
    ```
    
    Results
    ===================================== 
    
    ```{r}
    head(mydata)
    ```


Solution

  • As mydata is a reactive, you have to evaluate it with mydata() in a reactive context (e.g. renderDT). For more information, see flexdashboard with shiny and a shiny tutorial.

    ---
    title: "test"
    runtime: shiny
    output:
      flexdashboard::flex_dashboard:
      orientation: columns
    vertical_layout: fill
    theme: bootstrap
    ---
      
    
        ```{r global, include = FALSE}
        
        library(flexdashboard)
        library(tidyverse)
        library(DT)
        
        ```
        
        Sidebar {.sidebar}
        =====================================
        
        ```{r}
        
        fluidRow(
          column(7,
                 selectInput("Species", "Choose a species",
                             choices = c("setosa", "versicolor", "virginica"))))
        
        mydata <- reactive({
        iris %>% filter(Species == input$Species)
        })
        
        ```
        
        Results
        ===================================== 
        
        ```{r}
        renderDT({head(mydata())})
        ```