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

如何在ShinyApp中计算筛选后数据的总和?

ShinyApp筛选后数据总和计算问题解决

开发第一个ShinyApp时,需求是通过类别、目标群体两个筛选器,展示筛选后的福利预算数据表,并计算对应数据的总金额。当前代码能生成表格,但总和始终是全量数据的总和,无法匹配筛选结果。

原代码核心问题

  • output$Total直接计算整个Budget2023数据集的金额总和,未关联筛选后的结果
  • 筛选逻辑未考虑"全选"场景,且变量名存在拼写不一致(Broad_categories identified vs Broad_categories_identified)
  • 未复用筛选逻辑,表格和总和的数据源不一致

修改后的完整代码

library(shiny)
library(dplyr)
library(readxl)
library(shinythemes)

# 修正数据集示例(补全缺失元素,修正DF为data.frame)
Budget2023 <- data.frame(
  Welfare_benefit = c('A','B', 'C', 'D', 'E', 'F', 'G'),
  Value_in_Rupees_Million = c(43000, 67000, 3000, 250, 5700, 340, 3100), 
  Broad_categories_identified = c('Economic', 'Education', 'Health', 'Education', 'Livelihood', 'Education', 'Education'),
  Targetted_group = c('Elderly', 'Disabled', 'Children', 'Low income', 'Elderly', 'Disabled', 'Disabled')
)

# 读取真实数据时保留以下代码(替换上面的示例数据)
# Budget2023 <- read_excel("Budget2023.xlsx", sheet = "Welfare benefits for R")
# Budget2023$Value_in_Rupees_Million <- as.numeric(Budget2023$Value_in_Rupees_Million)

ui <- fluidPage(
  theme = shinytheme("superhero"),
  titlePanel("Budget 2023 - Welfare allocations"),
  
  sidebarLayout(
    sidebarPanel(
      # 添加"全部"选项,统一变量名
      selectInput("category",
                  "Select category",
                  choices = c("全部", unique(Budget2023$Broad_categories_identified))),
      selectInput("group",
                  "Select the targeted group",
                  choices = c("全部", unique(Budget2023$Targetted_group)))
    ),
    
    mainPanel(
      tableOutput("WelfareTable"),
      h4("筛选后总金额(百万卢比):"),
      textOutput("Total")
    )
  )
)

server <- function(input, output) {
  
  # 创建反应式数据集,统一处理筛选逻辑
  filtered_data <- reactive({
    data <- Budget2023
    # 处理类别筛选
    if (input$category != "全部") {
      data <- data %>% filter(Broad_categories_identified == input$category)
    }
    # 处理目标群体筛选
    if (input$group != "全部") {
      data <- data %>% filter(Targetted_group == input$group)
    }
    data
  })
  
  # 基于反应式数据生成表格
  output$WelfareTable <- renderTable({
    filtered_data()
  })
  
  # 基于反应式数据计算总和,格式化输出
  output$Total <- renderText({
    total <- sum(filtered_data()$Value_in_Rupees_Million, na.rm = TRUE)
    paste0(format(total, big.mark = ","))
  })
}

shinyApp(ui = ui, server = server)

关键修改说明

  • 反应式数据集filtered_data:将筛选逻辑抽离为反应式对象,表格和总和均基于该数据生成,确保数据源完全一致
  • 添加"全部"选项:支持用户查看所有类别/群体的数据,优化交互体验
  • 变量名统一:修正原代码中变量名的拼写差异,避免筛选失效
  • 总和计算优化:添加na.rm = TRUE处理缺失值,用format()添加千分位分隔符,提升可读性
  • UI细节优化:为总和添加标题,让输出结构更清晰

内容的提问来源于stack exchange,提问作者Dilshani N Ranawaka

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 17:15:37