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

Shiny应用:基于selectInput筛选计算Sold列总和报错求助

解决Shiny应用中filter筛选值匹配的错误问题

错误原因

你判断的没错:.data[[input$x]]的作用是引用数据框中的列名,但input$x获取的是selectInput选中的Car_Col的具体取值(比如"Red"),这时候用.data[[input$x]]会试图在数据框中查找名为"Red"的列,而你的数据里只有Car_Col/Car_Type/Sold三列,所以触发了列不存在的错误。

修正方案

直接用input$x和input$x2作为匹配值即可,不需要借助.data语法(.data是动态引用列名时才需要用的)。

完整修正代码

library(tidyverse)
library(shiny)
library(shinydashboard)

df <- 
  data.frame(Car_Col = c("Red","Blue","Red","Black","White","Black","Black","White","Red","Blue"),
             Car_Type = c("E","G","D","G","G","D","G","D","E","G"),
             Sold = c(1,0,1,0,0,0,1,1,0,0))

ui <- dashboardPage(
  dashboardHeader(),
  dashboardSidebar(),
  dashboardBody(
    fluidRow(
      selectInput(
        inputId = "x",
        label = "Select Car Color",
        choices = unique(df$Car_Col),
      )),
    selectInput(
      inputId = "x2",
      label = "Select Car Type",
      choices = unique(df$Car_Type)
    ),
    valueBoxOutput("box1")
  )
)

server <- function(input, output) {
  
  output$box1 <- renderValueBox({
    df %>% 
      filter(Car_Col == input$x) %>% 
      filter(Car_Type == input$x2) %>% 
      summarise(Number_Sold = sum(Sold)) %>% 
      pull(Number_Sold) %>% 
      valueBox(subtitle = "Number of sales")
  })
}

shinyApp(ui, server)

验证效果

当选择Car_Col=Red、Car_Type=E时,筛选后的数据是第1行和第9行,对应的Sold值为1和0,总和为1,valueBox会正确输出该结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 18:01:18