Home > database >  Filtering and adjusting data table
Filtering and adjusting data table

Time:04-02

I am attempting to display a dataframe with multiple pickerInput variables. When filtering by one variable, in the following example, species, it works fine. However, I can't seem to figure out how to format the sub setting code when trying to filter the dataframe by a second (and eventually a third variable)

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("sepal_width_input", "Sepal", choices = results$Sepal.Width, options = list(`actions-box` = TRUE), selected=NULL, multiple=TRUE)),
    
    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)

I included a second pickerInput behind a hashtag. Can someone tell me how the following code snippet should be formatted when including both variables?

mydata <- reactive({
        if (is.null(input$speciesInput)) {df <- results
        } else df <- results[results$Species %in% input$speciesInput,]
        df
      })

CodePudding user response:

You could write a function that handles the filtering, and pass the inputs to that function, like this:

library(shiny)
library(shinyWidgets)
library(DT)

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

filter_data <- function(spec=NULL, sepw=NULL) {
  res <- results
  if(!is.null(spec)) res <- res %>% dplyr::filter(Species %in% spec)
  if(!is.null(sepw)) res <- res %>% dplyr::filter(Sepal.Width %in% sepw)
  return(res)
}

# UI
ui <- fluidPage(
  
  # Application title
  titlePanel(
    h1("Iris Table", align="center")
  ),
  
  fluidRow( 
    column(3, 
          pickerInput("sepal_width_input", "SepalWidth", choices = results$Sepal.Width, options = list(`actions-box` = TRUE), selected=NULL, multiple=TRUE)),
    
    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({
    filter_data(input$speciesInput, input$sepal_width_input)
  })
  
  output$table <- DT::renderDataTable(
    datatable(mydata())
  )
  
}

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