Search code examples
rgroup-byshinybackticks

How to use group_by_() with shiny and back ticks>


I want my example to work. When I do not use back ticks and for example change Miles Per Gallon to MilesPerGallon then it correctly groups by the column. However, as soon as I put it in back ticks it won't work.

library(shiny)
library(DT)
library(tidyverse)

ui <- fluidPage(

   titlePanel("Old Faithful Geyser Data"),

   sidebarLayout(
      sidebarPanel(

        selectInput("groups", "Choose Groupings", choices = "Miles Per Gallon", multiple = TRUE, selected = "")

      ),


      mainPanel(

        DT::dataTableOutput("data")

      )
   )
)


server <- function(input, output) {

  output$data <- DT::renderDataTable({

    mtcars %>%
      select(`MilesPerGallon` = mpg, cyl, wt) -> dat

    if(length(input$groups) == 0) {

     dat

    } else {

      dat %>%
        dplyr::group_by_(input$groups) %>%
        summarise(n = n())

    }


  })

}

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

Solution

  • Use group_by_at which accepts string input.

    library(shiny)
    library(DT)
    library(tidyverse)
    
    ui <- fluidPage(
    
      titlePanel("Old Faithful Geyser Data"),
      sidebarLayout(
          sidebarPanel( 
          selectInput("groups", "Choose Groupings", choices = "Miles Per Gallon", 
                        multiple = TRUE, selected = "") 
    ),
    
    mainPanel(  
      DT::dataTableOutput("data")
        )
      )
    )
    
    server <- function(input, output) {
        output$data <- DT::renderDataTable({
        mtcars %>%
          select(`Miles Per Gallon` = mpg, cyl, wt) -> dat
    
        if(length(input$groups) == 0) {
         dat
       } else {
          dat %>%
             dplyr::group_by_at(input$groups) %>%
             summarise(n = n())
         }
       })
    }
    # Run the application 
    shinyApp(ui = ui, server = server)
    

    enter image description here