Marta
Marta

Reputation: 3162

Grouped select input with only one item

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?

Upvotes: 4

Views: 966

Answers (3)

wch
wch

Reputation: 4117

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")

Upvotes: 0

lroha
lroha

Reputation: 34601

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")
  ))
)

Upvotes: 2

user11538509
user11538509

Reputation:

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

Upvotes: 3

Related Questions