Detect numeric variables of a dataset and aggreagate them based on shiny widget selection of a categorical variable

In my shiny app I want to select one of my categorical variables and then detect and aggregate the numerical columns based on that selection.

## app.R ##
library(shiny)
library(shinydashboard)
library(shinyjs)
library(htmlwidgets)
library(DT)
ui <- dashboardPage(
  dashboardHeader(
    title="Task Managers' Workload Analysis",
    titleWidth = 400
    
  ),
  dashboardSidebar(
    selectInput("var","Select variable",choices = c("color","cut","clarity"),selected = "color")
  ),
  dashboardBody(
    dataTableOutput("table")
  )
)

server <- function(input, output,session) {
  output$table<-renderDataTable({
    datatable(
      D<-aggregate(diamonds, by = diamonds[[input$var]], FUN = sum)
      
    )
    
  })
} 

shinyApp(ui, server)

>Solution :

You may use across to do this –

diamonds %>% summarise(across(where(is.numeric), sum), .by = input$var)

Complete code –

library(shiny)
library(shinydashboard)
library(shinyjs)
library(htmlwidgets)
library(DT)
library(dplyr)

ui <- dashboardPage(
  dashboardHeader(
    title="Task Managers' Workload Analysis",
    titleWidth = 400
    
  ),
  dashboardSidebar(
    selectInput("var","Select variable",
        choices = c("color","cut","clarity"),selected = "color")
  ),
  dashboardBody(
    dataTableOutput("table")
  )
)

server <- function(input, output,session) {
  output$table<-renderDataTable({
    datatable(
      diamonds %>%
        summarise(across(where(is.numeric), sum), .by = input$var)
    )
    
  })
} 

shinyApp(ui, server)

enter image description here

Leave a Reply