Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading