I am building a Shiny app, where I have a selectizeInput. The options to select are country Names, stored in a data.frame along their three-digit codes.
Country
name | code |
---|---|
Aruba | ABW |
Afghanistan | AFG |
... | ... |
In my shiny app, I call selectizeInput, in the UI-part like this:
selectizeInput(inputId = 'inSelect',
label = "countries",
choices = country$name,
multiple = TRUE,
options = list(maxItems = 4,
placeholder = 'select up to 4 countries'))
When selecting countries, I get a list of the names of them in the inSelect variable.
e.g. when I select Afghanistan, inSelect has the Value Afghanistan.
Is there a possibility, to get a different Value as the output. So not the Name, but the code, stored next to it in the Table?
e.g. when I select Afghanistan, InSelect gets the Value AFG.
I know, that I can write the choice names down alongside their values. But Country is a table of ~200 rows.
Here's a quick app that does what you want, in short you can define the countries as names for the vector code
library(shiny)
country <- c("Aruba","Afghanistan")
code <- c("ABW","AFG")
choices <- code
names(choices) <- country
ui <- fluidPage(
selectInput(inputId = 'inSelect',
label = "countries",
choices = choices
multiple = TRUE),
textOutput("selected")
)
server <- function(input, output) {
output$selected <- renderText({
input$inSelect
})
}
shinyApp(ui = ui, server = server)
For your purposes, for data.frame df
use:
choices <- df$code
names(choices) <- df$country
This way the association between the two is defined as a single vector on app load, and you don't need to look up the codes in the table over and over (this answer is faster).