Seyma Kalay
Seyma Kalay

Reputation: 2863

Multiple group by and multiple tables at the same time in shiny

taking to the following code, I would like to see the multiple tables separately and at the same time. How to get around with this?

 library(dplyr)
library(shiny)

iris$Species2 <- iris$Species

ui <- fluidPage(
  
  selectInput(inputId ="column",
              label = "Choose Column for Summary",
              choices = c("Species", "Species2"),
              selected = "Species", multiple = T),
  
  DT::dataTableOutput('mytable')
)

server <- function(input, output) {
  output$mytable <- DT::renderDataTable({
    Summarise <-
      iris %>%
      dplyr::group_by(across(all_of(input$column))) %>% 
      summarise(mean1 = mean(Sepal.Length))
    DT::datatable(data = Summarise)
  })
  
}

# Run the application 
shinyApp(ui = ui, server = server)

Expected Answer

  Species    mean1   
  <fct>      <dbl> 
1 setosa      5.01  
2 versicolor  5.94  
3 virginica   6.59  

Species2    mean1   
  <fct>      <dbl> 
1 setosa      5.01  
2 versicolor  5.94  
3 virginica   6.59 

Upvotes: 0

Views: 451

Answers (1)

YBS
YBS

Reputation: 21349

One way to do is shown below.

library(dplyr)
library(shiny)
library(DT)

iris$Species2 <- iris$Species

ui <- fluidPage(
  
  selectInput(inputId ="column",
              label = "Choose Column for Summary",
              choices = c("Species", "Species2"),
              selected = "Species", multiple = T),
  uiOutput("t1")
  #DTOutput('mytable')
)

server <- function(input, output) {
  SummaRise <- reactive({
    req(input$column)
    
    if (length(input$column)>1) {
      df1 <- iris %>%
        dplyr::group_by(across(all_of(input$column[1]))) %>%
        dplyr::summarise(mean1 = mean(Sepal.Length))
      df2 <- iris %>%
        dplyr::group_by(across(all_of(input$column[2]))) %>%
        dplyr::summarise(mean1 = mean(Sepal.Length))
    } else {
      df1 <- iris %>%
        dplyr::group_by(across(all_of(input$column))) %>%
        dplyr::summarise(mean1 = mean(Sepal.Length))
      df2 <- NULL
    }
    return(list(d1 = df1, d2 = df2))
  })
  
  output$mytable1 <- renderDT({datatable(SummaRise()[["d1"]])})
  output$mytable2 <- renderDT({datatable(SummaRise()[["d2"]])})
  
  output$t1 <- renderUI({
    tagList(
      DTOutput("mytable1"),
      DTOutput("mytable2")
    )
  })
}

# Run the application
shinyApp(ui = ui, server = server)

output

Upvotes: 2

Related Questions