5

How do I get the group name from the selected input in a selectInput dropdown box with grouped choices? For example, how do I get Building after I select Bank within Building and Nature after I select Bank within Nature?

Updated example:

# 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)
    })
  }
)

One way is to store a variable of all choices and their grouped labels and search which group this choice is from. But this does not work when there are overlapping choices between groups.

Zhe Wang
  • 53
  • 5
  • you could save the list in a variable `lst` and then get the name of the list via `names(which(sapply(lst, "%in%", x = input$state)))` – Tonio Liebrand Jan 28 '19 at 21:18
  • 1
    @BigDataScientist Thank you for the comment. Yes, this works if the choices are unique among the groups. But what if there are overlapping choices within different groups? Is there a general way to deal with this situation? – Zhe Wang Jan 28 '19 at 21:36
  • what would be the desired output then: Both, the first, the last? – Tonio Liebrand Jan 28 '19 at 21:44
  • @BigDataScientist The question and example have been updated. Hope this answers your question. – Zhe Wang Jan 29 '19 at 16:08

1 Answers1

0

You can give each input a value instead of using their name directly, as follows:

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)
    })
  }
)
  • 1
    I guess I can concatenate the group name and the choice name to be the value for each choice to make them unique. Thanks. – Zhe Wang Jan 29 '19 at 16:56