RShiny使用selectInput实现NBA球队联盟筛选后renderTable输出问题
问题原因
你原来的服务端逻辑没有关联联盟选择组件的输入值,渲染表格时直接调用了全量的nba数据集,所以筛选不生效。另外你代码里用了filter函数但没有加载dplyr包,运行时也会报错。
修复方案
仅需要对服务端逻辑做少量调整即可:
- 补充加载dplyr包(用于数据过滤)
- 新增响应式数据对象,根据用户选择的联盟动态过滤球队
- 渲染表格时调用过滤后的响应式数据,同时增加校验避免未选指标时出现报错
修改后完整代码
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
相关产品推荐
相关产品推荐

