dave_in_newengland
dave_in_newengland

Reputation: 251

Using group_by with checkboxGroupInput in simple Shiny example

I was trying to use group_by with an input from checkboxGroupInput in a simple shiny app shown below.

I was expecting that if I checked 2 boxes (Cylinders and Gears) that I would get the same output as I get when I run this:

   mtcars%>%
     group_by(cyl, gear) %>%
     count()

# A tibble: 8 x 3
# Groups:   cyl, gear [8]
    cyl  gear     n
  <dbl> <dbl> <int>
1     4     3     1
2     4     4     8
3     4     5     2
4     6     3     2
5     6     4     4
6     6     5     1
7     8     3    12
8     8     5     2

Here is the simple shiny app. How would I mimic the above output when I check the boxes that are created from the below code?

# UI
    ui <- fluidPage(


  checkboxGroupInput("variable", "Variables to show:",
                     c("Cylinders"    = "cyl",
                       "Transmission" = "am",
                       "Gears"        = "gear"
                       )
                     ),
  tableOutput("data")
)


# Server
server <- function(input, output) {

    output$data <- renderTable({

      mtcars %>%
        group_by(!!as.name(input$variable)) %>%
        count()

      },
    rownames = TRUE)

  } # Server function close


# Run the app
  shinyApp(ui, server)

Thanks!

Upvotes: 1

Views: 253

Answers (1)

akrun
akrun

Reputation: 886948

In the server, we can change it to group_by_at which takes string input and it would accommodate more than one group variable input by wrapping with vars

server <- function(input, output) {

    output$data <- renderTable({

     mtcars %>%
         group_by_at(vars(input$variable)) %>%
         count()

      },
     rownames = TRUE)

  }

Also, in the OP's code, group_by could potentially take more than one groups, so we can convert to symbol with syms (more multiple elements) and then evaluate (!!!). If we use sym and !!, it would work only for one variable at a time

server <- function(input, output) {


  output$data <- renderTable({

    mtcars %>%
      group_by(!!! rlang::syms(input$variable)) %>%
      count()

  },
    rownames = TRUE)

}

-output

enter image description here

Upvotes: 1

Related Questions