How do I get aggregated data for selected attributes from shiny app?

143 Views Asked by At

It would be great someone can help to solve below criteria.

Requirement details:-

How to pass multiple attributes dynamically to group_by/summaries clause to get aggregated data for selected attributes? in my case I am able to achieve the same by using below code, but it was restricted to 1 group by attribute and summary attribute. If I select multiple group by or summary attributes, it's throwing error.

library(dplyr) 
library(data.table) 
library(shiny) 
library(DT)


df1 <- data.frame("name"=c("AAA","BBB","CCC"),"dept"=c("HR","HR","FIN"),"Salary"=c(1000,1345,5678),"Salary2"=c(4567,7896,5678))

ui <- fluidPage(
  sidebarLayout(
    sidebarPanel(
  pickerInput("Id0001","group by attributes",choices = unique(names(df1)),multiple = TRUE,options = list(`live-search` = TRUE)),
  pickerInput("Id0002","summary attributes",choices = unique(names(df1)),multiple = TRUE,options = list(`live-search` = TRUE)),
  actionButton("Id0003", "show data")
  ),
  mainPanel( DT::DTOutput("data_tbl") )
  )
)

server <- function(input,output,session){
  
  
  reactive_string  <- eventReactive(input$Id0003, {
    if (input$Id0003 > 0) {
      dt_agg_ui <<- df1  %>%
        group_by(!!rlang::sym(input$Id0001)) %>% 
        summarise_at(vars(!!rlang::sym(input$Id0002)),funs(sum,n()))
    }
    dt_agg_ui
  })
  
  output$data_tbl <- DT::renderDT( {reactive_string()})
  }
shinyApp(ui = ui, server = server)

Working shiny screenshot with single group by and summary attribute

Error shiny screenshot with multiple group by and summary attributes:-

1

There are 1 best solutions below

3
On BEST ANSWER

Using dplyr::across and tidyselect::all_of this could be achieved like so:

library(dplyr) 
library(data.table) 
library(shiny) 
library(shinyWidgets) 
library(DT)


df1 <- data.frame("name"=c("AAA","BBB","CCC"),"dept"=c("HR","HR","FIN"),"Salary"=c(1000,1345,5678),"Salary2"=c(4567,7896,5678))

ui <- fluidPage(
  sidebarLayout(
    sidebarPanel(
      pickerInput("Id0001","group by attributes",choices = unique(names(df1)),multiple = TRUE,options = list(`live-search` = TRUE)),
      pickerInput("Id0002","summary attributes",choices = unique(names(df1)),multiple = TRUE,options = list(`live-search` = TRUE)),
      actionButton("Id0003", "show data")
    ),
    mainPanel( DT::DTOutput("data_tbl") )
  )
)

server <- function(input,output,session){
  
  
  reactive_string  <- eventReactive(input$Id0003, {
    if (input$Id0003 > 0) {
      dt_agg_ui <<- df1  %>%
        group_by(across(all_of(input$Id0001))) %>% 
        summarise(across(all_of(input$Id0002), .fns = list(sum = sum, n = ~ n())))
    }
    dt_agg_ui
  })
  
  output$data_tbl <- DT::renderDT( {reactive_string()})
}
shinyApp(ui = ui, server = server)

enter image description here