You need to enable JavaScript to run this app. RShiny使用selectInput实现NBA球队联盟筛选后renderTable输出问题
优惠活动
大模型
产品
解决方案
定价
更多

RShiny使用selectInput实现NBA球队联盟筛选后renderTable输出问题

问题原因

你原来的服务端逻辑没有关联联盟选择组件的输入值,渲染表格时直接调用了全量的nba数据集,所以筛选不生效。另外你代码里用了filter函数但没有加载dplyr包,运行时也会报错。

修复方案

仅需要对服务端逻辑做少量调整即可:

  1. 补充加载dplyr包(用于数据过滤)
  2. 新增响应式数据对象,根据用户选择的联盟动态过滤球队
  3. 渲染表格时调用过滤后的响应式数据,同时增加校验避免未选指标时出现报错

修改后完整代码

library(shiny)
library(ggplot2)
library(jsonlite)
library(dplyr) # 新增dplyr包加载

# 读入数据
nba <- read.csv(file.choose())

ui <- fluidPage(
    tags$img(height=150, width=830,src = "NBAlogo2.png"),
    tabsetPanel(
        # General
        tabPanel(title = "General",
                 titlePanel("NBA Team Performance Metrics Analysis"),
                 sidebarLayout(
                     sidebarPanel(
                         p("This application allows you to compare and contrast several performance metrics amongst teams in the NBA."),
                         tags$img(height=100, width=100,src = "Eastern.png",align="center"),
                         tags$img(height=100, width=100,src = "Western.png"),
                         
                         # Team Filter
                         selectInput("conference", label = h3("Select Conference"),
                                     choices = list("Eastern", "Western")),

                         # Stat Filter
                         checkboxGroupInput("general", label = h3("General Metrics"), 
                                            choices = list("Winning Percentage" = "REC",
                                                           "Points" = "PTS")),
                     ),
                     mainPanel(
                         # Metric Output
                         h3("General Metrics"),
                         tableOutput("data1"),
                     ),
                 )
        )        
    )
)

server <- function(input, output) {
    # 响应式过滤:根据选择的联盟返回对应球队数据
    filtered_nba <- reactive({
      filter(nba, Conference == input$conference)
    })
   
    #  General
    output$data1 <- renderTable({
      req(input$general) # 避免未选指标时抛出错误
      filtered_nba()[,c("Team",input$general)]
    }, rownames = TRUE)
}

shinyApp(ui = ui, server = server)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.20 17:06:03