Shiny 应用程序中分组依据的描述性统计

descriptive statistics with group by in Shiny app

我有一个示例工作代码如下。结果应该group(基于Species and/or Species2)然后打印出Sepal.Length和Sepal.Width的mean。我很感激。

    library(shiny)
library(dplyr)

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(groupby = input$column) %>% 
      summarise( mean1 = mean(iris$Sepal.Length))
    DT::datatable(data = Summarise)
  })
  
}

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

预期答案;

a <- iris %>% 
  dplyr::group_by(Species) %>%
  dplyr::summarise( mean1 = mean(Sepal.Length)); a


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

您可以在 group_by 中使用 across,这样您就可以按多个输入进行分组。

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)