I want to group a data.frame based on a column the user can choose as an input. Therefore I use the group_by
function in the dplyr
package.
However, input$variable
is a string, so this won't work in group_by
, which expects the variable. I am not sure how to change the code to make this work:
library(shiny)
library(dplyr)
df <- data.frame(
a = c("a1", "a2", "a1"),
d = c("d1", "d1", "d2"),
b = c(2, 4, 5)
)
ui <- fluidPage(
selectInput("variable", "Select a variable", choices = c("a", "d"), selected = "a"),
tableOutput("table")
)
server <- function(input, output) {
output$table <- renderTable({
df %>% group_by(input$variable) %>% summarise(the_sum = sum(b))
# this would work: df %>% group_by(a) %>% summarise(the_sum = sum(b))
})
}
shinyApp(ui, server)
Any ideas on how to solve this?