selectInput does not display default

The following problem is abstracted from a webapp I am currently working on. In the actual version, the choices for the selectInput are imported and change based on previous user Input (thats why I am using renderUI).

The problem is the following: The input box does not show a default value (it actually does not have a value, as I get error messages from the calculations based on the input, at default).

library(shiny)

test <- c('AC-50', 'AC-50', 'AC-35x2 Dual Motor', 'AC-35x2 Dual Motor')
test2 <- c('a','b','c','d')

ui <- fluidPage(
  uiOutput("test")
  )

server <- function(input, output){
  output$test <- renderUI({
    selectInput("test", "Select:", choices=test)
  })
}

shinyApp(ui = ui, server = server)

A couple of further observations that arose during my attempts at troubleshooting:

  • Oddly, this is only the case if choices is set to 'test'. 'test2' (random strings created for troubleshooting purposes) returns a default value
  • Playing around with selected=NULL seems to have no effect

I am by no means a Shiny (or R) expert, so I might be overlooking something, but any help would be appreciated.

Just wondering why you have duplicate values in the choices? if you make them unique, the default value will be set

test <- unique(c('AC-50', 'AC-50', 'AC-35x2 Dual Motor', 'AC-35x2 Dual Motor'))

2 Likes

Hello,

I'd like to add to @ginberg suggestion. It is indeed a good idea to keep the values unique and even sort them for the user to use the selection input with the most ease.

I do suggest however that you use the updateSelectInput statement instead of creating a renderUI function. It will make your code cleaner and more intuitive. Here is my example:

library(shiny)

test <- c('AC-50', 'AC-50', 'AC-35x2 Dual Motor', 'AC-35x2 Dual Motor')
test2 <- c('a','b','c','d')

ui <- fluidPage(
  selectInput("input1", "Select:", choices = "")
)

server <- function(input, output, session){
  
  updateSelectInput(session, "input1", 
                    choices = sort(unique(test)), 
                    selected = sort(unique(test))[2]
                    )

}

shinyApp(ui = ui, server = server)
  • Note that I created am empty selectInput in the UI, but I use the corresponding updateSelectInput at server level to assign the correct values. Every UI input has its corresponding update function in case you like to update it at server level.
  • You need to add a session statement to your server function in order to work with updateSelectInput (don't worry too much about it, it just ensures Shiny knows which UI elements to render or update for which user)
  • You can set any desired value as the default value of an input by just assigning a value of the choices to the selected argument

Hope this helps,
PJ

2 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.