【问题标题】:Shiny: Generating a selectInput from a list of lists goes directly to the deepest layerShiny:从列表列表中生成 selectInput 直接进入最深层
【发布时间】:2021-08-03 21:08:08
【问题描述】:

我正在尝试使用一个高度嵌套的列表(6 层)作为生成一系列下拉菜单的基础。但是,当通过 selectInput 函数传递嵌套列表时,最深的层就是选择的内容。下面是一个简单的应用程序来重现我遇到的问题。

    library(shiny)

    problemList <- list(
      deeperList = list (
        element1 = 1,
        element2 = 2
      ),
      deeperList2 = list (
        element3 = 3,
        element4 = 4
      )
    )

    ui <- fluidPage(
      selectInput(inputId = "dropDownMenu", label = "Drop Down Menu", choices = problemList)
    )

    server <- function(input, output) {}

    shinyApp(ui = ui, server = server)

Image showing what is generated by the code above

我试图让用户在第一个下拉菜单中选择 deepList 和 deepList2。如果他们选择 deepList,则会生成另一个下拉菜单,允许用户在 element1 和 element2 之间进行选择,但如果他们选择 deepList2,则会生成另一个下拉菜单,允许用户在 element3 和 element4 之间进行选择。

【问题讨论】:

    标签: r shiny


    【解决方案1】:

    基本上有两种方法可以做到这一点。

    1. 使用renderUI 创建第二个下拉列表。通过这样做,您可以使第二个下拉菜单的选择取决于第一个下拉菜单的选择。请参阅here 中的“使用 renderUI 动态创建控件”部分。
    2. 当第一个下拉菜单发生变化时,使用updateSelectInput 更新第二个下拉菜单

    这是第二个选项的示例

    library(shiny)
    
    problemList <- list(
      deeperList = list(
        element1 = 1, element2 = 2),
      deeperList2 = list(
        element3 = 3, element4 = 4)
    )
    
    ui <- inputPanel(
      selectInput("category", "choose a category", names(problemList)),
      selectInput("choice", "select a choice", problemList[[1]])
    )
    
    server <- function(input, output, session) {
      observe({
        updateSelectInput(session, "choice", choices = problemList[[input$category]])
      })
    }
    
    shinyApp(ui, server)
    

    在大多数情况下,选项 2 应该更好,因为根据输入重新渲染 UI 会导致一些奇怪的错误和糟糕的性能。

    【讨论】:

    • 非常感谢!完美运行。
    猜你喜欢
    • 2020-05-02
    • 2020-07-20
    • 1970-01-01
    • 1970-01-01
    • 2014-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-21
    相关资源
    最近更新 更多