You need to enable JavaScript to run this app. Shiny应用SelectInput无法基于所选CSV动态填充选项且报contents2未找到错误
优惠活动
大模型
产品
解决方案
定价
更多

Shiny应用SelectInput无法基于所选CSV动态填充选项且报contents2未找到错误

问题根源

  • selectInput无下拉选项:UI层selectInput的choices参数写的c(colnames(DT::dataTableOutput("mydata")))逻辑完全错误:DT::dataTableOutput是生成前端表格占位符的函数,不会返回实际数据,且mydata这个output对象从未定义,自然取不到列名,最终选项为空。
  • object 'contents2' not found报错:output$contents2是专门用于前端表格渲染的输出对象,不是存储底层数据的变量,server端绘图逻辑不能直接调用它取数;同时读取的myfile是observeEvent内的局部变量,作用域仅限该事件内部,其他响应式函数(如renderPlot、动态更新输入)完全无法访问。
  • 附加问题:代码里直接用了read_csv但未加载对应包,会额外触发报错。

解决方案

  1. 用reactive()存储读取的文件数据,让所有server端响应式逻辑都能访问该数据,避免局部变量作用域问题。
  2. 不在UI层硬写selectInput的选项,等文件读取完成后,在server端用updateSelectInput()动态填充列名,适配不同上传的文件。
  3. 绘图时直接从存储数据的reactive()变量取对应选中列,不调用前端输出的渲染对象。
  4. 补充缺失的包引用,或改用base R的read.csv读取文件。

修正后可运行代码

library(shinyWidgets)
library(shiny)
library(shinydashboard) 
library(readr) # 补充read_csv依赖

ui <-  dashboardPage(
  dashboardHeader(title="Test"),
  dashboardSidebar(
    sidebarMenu(id = 'sbar', verbatimTextOutput("text1"),
                menuItem("File Selection", tabName = 'page1', icon = icon('line-chart'),
                         fileInput("file1", "Select CSV File", accept = c("text/csv","text/comma-separated-values,text/plain",".csv")),
                         menuSubItem(actionButton(inputId="next1", label="NEXT"), tabName="next", 
                                     icon="") ),
                menuItem('File Edit', tabName = 'page2',icon = icon('line-chart')),
                menuItem('Section 3',tabName = 'page3',icon = icon('line-chart'))
    )
  ),
  dashboardBody(
    tabItems( 
      tabItem(tabName = "next",fluidRow(
        tabBox(id = "tabset1", height = "650px", width=12, 
               tabPanel("Input Data", value="tab1", " ",
                        radioGroupButtons("disp", "",label=NULL, 
                                          choices = c('Display head data'="head",'Display entire data'="all"), selected="head"),
                        fluidRow(DT::dataTableOutput("contents1"),style = "height:500px; overflow-y: scroll;overflow-x: scroll;",
                                 title = "Dashboard example") ),
               # 修正selectInput,留空choices待server动态更新
               tabPanel("Plot", value="tab2", " ",  
                        selectInput("select1","Select Variable for display",choices = NULL),
                        fluidRow(plotOutput("plot1"))),
               tabPanel("tab3 title", value='tab3', " ",
                        valueBoxOutput('tab3_valuebox'))
        ) 
      ) ),
      tabItem(tabName="page2", fluidRow(
        tabBox(id = "tabset2", height = "650px", width=12, title = "My Page2 info",
               tabPanel("Input Data", value="tab1", " ",
                        fluidRow(DT::dataTableOutput("contents2"))),
               tabPanel("Plot", value="tab2", " ",
                        fluidRow(plotOutput("plot2")) )
        ) 
      ) ) 
    )
  )
)

server <- function(input, output, session) {
  # 定义响应式变量存储读取的文件数据,全局可访问
  uploaded_data <- reactive({
    req(input$file1)
    read_csv(input$file1$datapath)
  })
  
  observeEvent(input$next1, {
    # 未上传文件时直接拦截,不执行后续逻辑
    req(input$file1)
    updateTabItems(session, "sbar", "next")
    
    # 动态更新selectInput的列名选项
    updateSelectInput(session, "select1", choices = colnames(uploaded_data()))
  })
  
  output$contents1 <- renderDataTable({
    req(uploaded_data())
    if(input$disp == "head") {
      return(head(uploaded_data()))
    }else {
      return(uploaded_data()) 
    }
  })
  
  output$contents2 <- renderDataTable({
    req(uploaded_data())
    uploaded_data()
  })
  
  output$text1 <- renderText(print(input$sbar))
  
  # 修正绘图逻辑,从响应式变量取数
  output$plot1 <- renderPlot({
    req(input$select1, uploaded_data())
    hist(uploaded_data()[[input$select1]])
  })
  
  output$plot2 <- renderPlot({hist(rnorm(20))})
  
  output$tab3_valuebox <- renderValueBox({
    valueBox('2020',subtitle = "Need to use this in future",icon = icon("car"),
             color = "red") 
  })
}  
shinyApp(ui, server)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.12.01 09:36:06