4

I wanted to group my selectInput data as explained here: https://shiny.rstudio.com/gallery/option-groups-for-selectize-input.html. Everything works except the situation where there is only one item in the group.

Here is an example (with correct first selectInput and strange second one):

library(shiny)

ui <- fluidPage(
    selectInput("country", "Select country", list(
        "Europe" = c("Germany", "Spain"),
        "North America" = c("Canada", "United States" = "USA")
    )),

    selectInput("country", "Select country", list(
        "Europe" = c("Germany", "Spain"),
        "North America" = c("Canada")
    ))
)

server <- function(input, output, session) {
}

shinyApp(ui = ui, server = server) 

And the effect:

enter image description here

Do you know how to deal with that?

Joris C.
  • 5,721
  • 3
  • 12
  • 27
Marta
  • 3,032
  • 3
  • 17
  • 34

3 Answers3

2

I do not know why this happens but this is how it works for me

library(shiny)

ui <- fluidPage(
  selectInput("country", "Select country", list(
    "Europe" = c("Germany", "Spain"),
    "North America" = c("Canada", "United States" = "USA")
  )),

  selectInput("country", "Select country", list(
    "Europe" = c("Germany", "Spain"),
    "North America" = c("Canada", "")
  ))
)

server <- function(input, output, session) {
}

shinyApp(ui = ui, server = server)

The only difference in code is that I added "" here "North America" = c("Canada", ""). This gives me

Output

1

You need to use list() instead of c() if there is a single element. If there is more than one element you can use either list() or c().

  ui <- fluidPage(
  selectInput("country", "Select country", list(
    "Europe" = list("Germany", "Spain"),
    "North America" = list("Canada", "United States" = "USA")
  )),

  selectInput("country", "Select country", list(
    "Europe" = list("Germany", "Spain"),
    "North America" = list("Canada")
  ))
)
Ritchie Sacramento
  • 29,890
  • 4
  • 48
  • 56
0

You need to use list() instead of c(), as in:

  selectInput("country", "Select country", list(
    "Europe" = list("Germany", "Spain"),
    "North America" = list("Canada")
  ))

The issue is with how R represents these things. "x" and c("x") are exactly the same thing, because in R, a scalar value is represented with a length-1 vector. To illustrate:

> identical("x", c("x")) 
[1] TRUE

So R has no way of distinguishing "x" from c("x"), but it can distinguish "x" from list("x")

wch
  • 4,069
  • 2
  • 28
  • 36