Shiny - 更改 selectInput() 中的选项数量

问题描述

我想更改 selectinput() 中的选项数量。如果新选项在数量上与原始选项相同,则以下 reprex 有效,但如果提供更多(或更少)选项,则代码不起作用。我怎样才能变得闪亮,不仅接受 selectinput() 的新选择,而且接受新的选择数量?在此先感谢您的帮助。

菲利普


    library(shiny)
    ui <- fluidPage(
      tabPanel("tbls",selectInput("tab1",label="Pick a table:",choices=c("a","b","c")),selectInput("cht1",label="Pick a time series:",choices=c("d","e","f"))
      )
    )
    server <- function(input,output,session) {
      Nchoices <- reactive({case_when(
        input$tab1=="a" ~c("d","f"),input$tab1=="b" ~c("g","h","i"),input$tab1=="c" ~c("j","k","l","m") # adding one more choice breaks the code
      )}) 
      observe({updateSelectInput(session,"cht1",choices=Nchoices(),selected=NULL)})
      observe(print(Nchoices()))
    
    }
    shinyApp(ui,server)

解决方法

尝试使用 case_when 代替 switch。此外,renderUI 可能有用。试试这个

library(shiny)
ui <- fluidPage(
  tabPanel("tbls",selectInput("tab1",label="Pick a table:",choices=c("a","b","c")),uiOutput("myselect")
           #selectInput("cht1",label="Pick a time series:",choices=c("d","e","f"))
  )
)
server <- function(input,output,session) {
  
  Nchoices <- reactive({
    switch(input$tab1,"a" = c("d","f"),"b" = c("g","h"),"c" = c("j","k","l","m") # adding one more choice breaks the code
    )
  })
  
  output$myselect <- renderUI({
    req(input$tab1)
    selectInput("cht1",choices=Nchoices())
  })
 
  observe(print(Nchoices()))
  
}
shinyApp(ui,server)

请注意,在 case_when 中,所有 RHS 值都必须属于同一类型。不一致的类型会抛出错误。