You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Shiny应用中按指定字段分组实现描述性统计的问题

Shiny分组描述统计功能修正方案

原代码存在的问题

  • 分组字段传入不符合dplyr整洁求值规则:input$column返回字符串向量,直接传入group_by会被识别为固定值而非数据集列,无法完成分组
  • 均值计算引用全局数据集:mean(iris$Sepal.Length)直接调用原始数据集列,统计的是全量数据均值而非分组后的分组均值
  • 缺少Sepal.Width的均值统计逻辑,仅输出了Sepal.Length的计算结果

修正后完整代码

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(across(all_of(input$column))) %>% 
      summarise(
        mean1 = mean(Sepal.Length),
        mean2 = mean(Sepal.Width),
        .groups = "drop"
      )
    DT::datatable(data = Summarise)
  })
  
}

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

效果说明

  • 单选Species或Species2时,输出单维度分组的Sepal.Length(mean1)、Sepal.Width(mean2)均值,和你预期的输出结果一致
  • 同时选中两个字段时,会自动按照两个字段的组合维度完成分组统计

内容的提问来源于stack exchange,提问作者symkly

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 01:39:07