Kyle Overton
Kyle Overton

Reputation: 49

R Shiny Custom User Filter with Checkboxes

I have data table output that I want users to be able to create their own custom table by using checkboxes to select which row/element they want. In the example below is a mtcars output. For example I want users to be able to pick say A Mazda, Fiat, Toyota, and a Dodge model using a check box. As far as trying any code, I haven't found any examples that come close.

library(shiny)

if (interactive()) {
    
    # basic example
    shinyApp(
        ui = fluidPage(
            selectInput("variable", "Variable:",
                        c("Cylinders" = "cyl",
                          "Transmission" = "am",
                          "Gears" = "gear"), multiple = T),
            tableOutput("data")
        ),
     server = function(input, output) {
            output$data <- renderTable({
                mtcars[, c("mpg", input$variable), drop = FALSE]
            }, rownames = TRUE)
        }
    )
    
}

Upvotes: 0

Views: 110

Answers (1)

Marcus
Marcus

Reputation: 3636

The general approach below is 1) create a checkbox group input listing the car names (i.e. rownames) as the names, having the corresponding values be the row numbers and 2) using those row numbers to filter your data.frame on the server.

Using the reactive rowsToUse will update every time the selection changes. It also allows the handling of the case when no rows are selecting (default to all rows in the example below).

shinyApp(

  ui = fluidPage(
    checkboxGroupInput(
      inputId = "variable", 
      label = "Cars:",
      choiceNames = rownames(mtcars),
      choiceValues = seq(NROW(mtcars))
    ),
    tableOutput("data")
  ),

  server = function(input, output) {
    
    rowsToUse <- reactive(
      
      if(is.null(input$variable)) {
        seq(NROW(mtcars)) 
      } else{ 
        as.numeric(input$variable)
      }
      
    )
    
    output$data <- renderTable({
      
      mtcars[rowsToUse(),  , drop = FALSE]
    }, rownames = TRUE)
  }

)

Upvotes: 1

Related Questions