在R的Shiny中使用updateCheckboxGroupInput时触发vroom报错
问题描述
尝试通过Shiny上传CSV文件,并用文件中的某列更新checkboxGroupInput组件。未添加该组件或对应的observeEvent/updateCheckboxGroupInput逻辑时程序运行正常,添加后出现如下错误:
Warning: Error in vroom::vroom:
fileis not one of the supported inputs:
• A filepath or character vector of filepaths
• A connection or list of connections
• Literal or raw input
122: <Anonymous>
121: signalCondition
120: signal_abort
119: rlang::abort
118: cli::cli_abort
117: standardise_path
116: vroom::vroom
115: read_csv
用户未显式使用vroom库,疑惑该错误出现的原因及与更新输入组件的关联,相关代码如下:
library(shiny) library(readr) holiday_movie_genres <- readr::read_csv("https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2023/2023-12-12/holiday_movie_genres.csv") write.csv(holiday_movie_genres, "hmg.csv") ui <- fluidPage( checkboxGroupInput("genre", "Select Genre", choices = NULL), fileInput("movie_file", "Upload File"), tableOutput("movie_table") ) server <- function(input, output, session) { movie_reactive <- reactive({ read_csv(input$movie_file$datapath) }) output$movie_table <- renderTable({ movie_reactive() }) observeEvent(movie_reactive(), { updateCheckboxGroupInput(inputId = "genre", choices = unique(movie_reactive()$genres)) }) } shinyApp(ui, server)
问题原因与解决办法
原因
- 初始化空值传递:程序启动时
input$movie_file为空,input$movie_file$datapath返回NULL,此时调用read_csv(NULL)会触发错误。 - 隐性依赖vroom:
readr::read_csv目前底层基于vroom库实现,因此错误信息会显示vroom的调用栈,即便未显式加载vroom。 - observeEvent触发时机:
observeEvent监听movie_reactive(),程序初始化时该reactive会执行一次,导致read_csv接收空值触发错误。
修复步骤
在读取文件的reactive逻辑中添加判断,确保仅当文件上传完成后才执行读取操作,可使用req()函数强制依赖文件输入:
修改后的完整代码:
library(shiny) library(readr) holiday_movie_genres <- readr::read_csv("https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2023/2023-12-12/holiday_movie_genres.csv") write.csv(holiday_movie_genres, "hmg.csv") ui <- fluidPage( checkboxGroupInput("genre", "Select Genre", choices = NULL), fileInput("movie_file", "Upload File"), tableOutput("movie_table") ) server <- function(input, output, session) { movie_reactive <- reactive({ # 确保文件已上传才执行读取 req(input$movie_file) read_csv(input$movie_file$datapath) }) output$movie_table <- renderTable({ movie_reactive() }) observeEvent(movie_reactive(), { updateCheckboxGroupInput(inputId = "genre", choices = unique(movie_reactive()$genres)) }) } shinyApp(ui, server)
内容的提问来源于stack exchange,提问作者mjrams73
相关产品推荐
相关产品推荐

