R Shiny selectInput开启多选后报Error in if参数长度为零错误
错误原因
开启multiple = TRUE的下拉框在未完成选择时,对应的input值为长度为0的空向量,直接放入if条件判断就会触发「argument is of length zero」报错;另外多选场景下输入值可能是长度大于1的向量,直接用!=做判断会返回多值逻辑向量,不符合if仅支持单逻辑值的要求。
修复方案
需要调整3部分逻辑:
- 给多选下拉框设置初始默认选中值为
"All",避免初始空值状态 - 所有
if判断先校验输入非空,再判断选中值中是否包含"All",适配多值场景 - 过滤逻辑中如果选中项包含
"All",直接跳过该维度的过滤操作
修复后完整可运行代码
library(shiny) library(DT) State <- c("NV", "NV","NV", "MD", "MD", "MD", "MD", "NY", "NY", "NY", "OH", "OH", "OH") County <- c("CLARK", "WASHOE", "EUREKA", "MONTGOMERY", "HOWARD", "BALTIMORE", "FREDERICK", "BRONX", "QUEENS", "WESTCHESTER", "FRANKLIN", "SUMMIT", "STARK" ) City <- c("Las Vegas", "Reno", "Eureka", "Rockville", "Columbia", "Baltimore", "Thurmont", "Bronx", "Queens", "Yonkers", "Columbus", "Akron", "Canton") Rating<- c(1,2,3,4,5,6,7,8,9,10,11,12,13) df <- data.frame(State, County, City, Rating, stringsAsFactors = F) ui <- fluidPage( titlePanel("Test Dashboard "), sidebarLayout( sidebarPanel( selectInput("data1", "Select State", choices = c("All", unique(df$State))), selectInput("data2", "Select County", choices = NULL, multiple = TRUE), selectInput("data3", "select City", choices = NULL, multiple = TRUE) ), mainPanel( DTOutput("table") ) )) server <- function(input, output, session){ observeEvent(input$data1, { if (!"All" %in% input$data1) { updateSelectInput(session, "data2", "Select County", choices = c("All", unique(df$County[df$State %in% input$data1])), selected = "All") } else { updateSelectInput(session, "data2", "Select County", choices = c("All", unique(df$County)), selected = "All") } }, priority = 2) observeEvent(c(input$data1, input$data2), { req(input$data2) if (!"All" %in% input$data2) { updateSelectInput(session, "data3", "Select City", choices = c("All", unique(df$City[df$County %in% input$data2])), selected = "All") } else { if (!"All" %in% input$data1) { updateSelectInput(session, "data3", "Select City", choices = c("All", unique(df$City[df$State %in% input$data1])), selected = "All") } else { updateSelectInput(session, "data3", "Select City", choices = c("All", unique(df$City)), selected = "All") } } }, priority = 1) filtered_data <- reactive({ req(input$data2, input$data3) temp_data <- df if (!"All" %in% input$data1) { temp_data <- temp_data[temp_data$State %in% input$data1, ] } if (!"All" %in% input$data2) { temp_data <- temp_data[temp_data$County %in% input$data2, ] } if (!"All" %in% input$data3) { temp_data <- temp_data[temp_data$City %in% input$data3, ] } temp_data }) output$table <- renderDT( filtered_data() ) } shinyApp(ui, server)
内容的提问来源于stack exchange,提问作者wizkids121
相关产品推荐
相关产品推荐

