littleworth
littleworth

Reputation: 5169

How to manually order the selected values in Shiny selectInput()

I have the following Shiny code:

library(shiny)

my_choices <- c( "a", "b", "c", "d")


ui <- fluidPage(
  selectInput(
    "d", "My Test", choices = my_choices, selected = c("c","a"), multiple = TRUE
  )
)

server <- function(input, output) {}

shinyApp(ui, server)

It produces the following UI: enter image description here

Note that in my code I specified that the selected input should be in the order of c("c", "a"). But the UI sort it as a -> c. How can I disable this auto-sorting in Shiny?

Upvotes: 2

Views: 709

Answers (1)

HubertL
HubertL

Reputation: 19544

You can reorder choices by setting selected order first:

library(shiny)

my_choices <- c( "a", "b", "c", "d")
my_selected <- c("c", "a")
my_new_choices = my_choices[ c(
  sapply(my_selected, FUN=function(i) which(my_choices == i)), 
  which(! my_choices %in% my_selected))]

ui <- fluidPage(
  selectInput(
    "d", "My Test", choices = my_new_choices, selected=my_selected, multiple = TRUE
  )
)

server <- function(input, output) {
}

shinyApp(ui, server)

Upvotes: 3

Related Questions