Adam Black
Adam Black

Reputation: 337

How to use selectize input with dplyr in Shiny?

I would like to make this simple app work correctly. It is supposed allow the user to select any number of variables in the dplyr::starwars dataset and display the distinct combinations of those variables.

library(shiny)
library(tidyverse)

ui <- fluidPage(
   titlePanel("Use selectize with dplyr"),
   selectizeInput("distinct_vars", "Select distinct", choices = names(starwars), multiple = T),
   dataTableOutput("table")
)

server <- function(input, output) {
   output$table <- renderDataTable({
        req(input$distinct_vars)
        arg_list <- rlang::parse_quosures(paste(input$distinct_vars, collapse = ";"))

        starwars %>% 
             distinct(!!arg_list)
   })
}

shinyApp(ui = ui, server = server)

I'm having difficulty with the line distinct(!!arg_list). I would like to pass arguments to the distinct function as a list. If I replace this line with distinct(!!arg_list[[1]]) then the app works correctly but only for the first variable selected. I would like to allow the user to select any number of variables and the pass the user's selection(s) on to dplyr functions.

Upvotes: 1

Views: 1144

Answers (1)

akrun
akrun

Reputation: 887531

For multiple vars, we need !!! instead of !!

 ui <- fluidPage(
   titlePanel("Use selectize with dplyr"),
   selectizeInput("distinct_vars", "Select distinct", choices = names(starwars), multiple = T),
   dataTableOutput("table")
)

server <- function(input, output) {
   output$table <- renderDataTable({
        req(input$distinct_vars)
        arg_list <- rlang::parse_quosures(paste(input$distinct_vars, collapse = ";"))

        starwars %>% 
             distinct(!!! arg_list)
   })
}

shinyApp(ui = ui, server = server)

-output

enter image description here

Upvotes: 3

Related Questions