如何处理R Shiny应用中的长度为0的错误?
问题描述
- 登录(用户名
user1,密码pass1)后应用立即报错,点击左侧面板的提交按钮后错误消失,应用恢复正常运行 - 选择当前日期时无内容展示,选择其他日期会根据所选气缸过滤器展示
mtcars数据集的聚合mpg数据 - 推测错误源于
if语句中空值与数值的比较,需消除该干扰问题
问题根源
登录后初始状态下,input$date1值为NULL,此时执行input$date1 == Sys.Date()会触发类型不匹配错误;同时input$cyl初始值也为NULL,后续逻辑中对空值的处理不够严谨,进一步引发报错。点击提交按钮后,reactive对象重新计算时,虽然输入值仍可能为空,但此时错误被后续逻辑覆盖,因此报错消失。
修改后的代码
library(shinydashboard) library(shiny) library(shinyauthr) library(dplyr) library(DT) # 用户信息数据集 user_base <- tibble::tibble( user = c("user1", "user2"), password = sapply(c("pass1", "pass2"), sodium::password_store), permissions = c("admin", "standard"), name = c("User One", "User Two") ) ui <- dashboardPage( dashboardHeader(title = "Hi", tags$li(class = "dropdown", style = "padding: 8px;", shinyauthr::logoutUI("logout"))), dashboardSidebar(uiOutput("tarikh_1"), uiOutput("cyls"), submitButton("submit")), dashboardBody( shinyauthr::loginUI(id = "login"), uiOutput("tabs") ) ) server <- function(input,output,session){ data <- mtcars output$tarikh_1 <- renderUI({ req(credentials()$user_auth) dateInput("date1","Date_1",value = NULL) }) output$cyls <- renderUI({ req(credentials()$user_auth) selectInput("cyl","选择气缸",choices = c('4','6','8'),multiple = TRUE) }) credentials <- shinyauthr::loginServer( id = "login", data = user_base, user_col = user, pwd_col = password, sodium_hashed = TRUE, log_out = reactive(logout_init()) ) # 登出逻辑 logout_init <- shinyauthr::logoutServer( id = "logout", active = reactive(credentials()$user_auth) ) table_1 <- reactive({ # 先判断date1是否为空,避免空值与日期比较报错 if(is.null(input$date1)){ return(NULL) } if(input$date1 == Sys.Date()){ return(NULL) }else{ f <- input$cyl # 处理cyl为空的情况,默认选中所有气缸 if(is.null(f)){ f <- c("4","6","8") } data %>% filter(cyl %in% f) %>% group_by(cyl) %>% summarise(Average_mileage = sum(mpg)) } }) output$non_bin <- renderDataTable({ table_1() }) output$tabs <- renderUI({ req(credentials()$user_auth) tabsetPanel(type = "tab", tabPanel("聚合计算",dataTableOutput("non_bin"))) }) } shiny::shinyApp(ui, server)
修改说明
- 在
table_1开头增加is.null(input$date1)判断,直接返回NULL避免空值与日期比较的类型错误 - 提前处理
input$cyl为空的情况,默认设置为所有气缸选项,简化原有的冗余逻辑 - 移除了不必要的
grps相关代码,让逻辑更简洁易懂 - 优化了界面文本的中文表述(可根据需求调整回英文)
修改后,登录初始状态下table_1返回NULL,不会触发DT组件的报错;用户选择日期或点击提交后,逻辑正常执行,完全符合原有功能需求。
内容的提问来源于stack exchange,提问作者joy_1379
相关产品推荐
相关产品推荐

