从 SelectInput (RShiny) 中的选项分组列表中获取组标签

Get the group label from a grouped list of choices in SelectInput (RShiny)

如何从带有分组选项的 selectInput 下拉框中的 selected 输入中获取组名?例如,如何在 Building select Bank 之后获得 Building 以及在 select Bank 之后如何获得 Nature Nature?

更新示例:

# demoing optgroup support in the `choices` arg
shinyApp(
  ui = fluidPage(
    selectInput("state", "Choose a word:",
      list(`Building` = list("Apartment", "Bank", "Hospital"),
           `Nature` = list("Bank", "River", "Orange"),
           `Color` = list("Blue", "Orange", "Red"))
    ),
    textOutput("result")
  ),
  server = function(input, output) {
    output$result <- renderText({
      paste("You chose", input$state)
    })
  }
)

一种方法是存储所有选项及其分组标签的变量,并搜索该选项来自哪个组。但是当组之间存在重叠选择时,这不起作用。

您可以给每个输入一个值,而不是直接使用它们的名称,如下所示:

shinyApp(
  ui = fluidPage(
    selectInput("state", "Choose a word:",
                list(`Building` = list("Apartment"="ap", "Bank"="bk", "Hospital"="hp"),
                     `Nature` = list("Bank"="bk1", "River"="rv", "Orange"="or"),
                     `Color` = list("Blue"="bl", "Orange"="or1", "Red"="rd"))
    ),
    textOutput("result")
  ),
  server = function(input, output) {
    output$result <- renderText({
      paste("You chose", input$state)
    })
  }
)