0

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.

Moritz
  • 67
  • 1
  • 6

2 Answers2

3

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

enter image description here

0

You can get the corresponding value on the server side using match.

Here's a quick and small shiny app.

library(shiny)

ui <- fluidPage({
  fluidRow(column(6, selectizeInput(inputId = 'inSelect',
                 label = "countries",
                 choices = country$name,
                 multiple = TRUE)), 
           column(6, verbatimTextOutput('text')))
  
})

server <- function(input, output) {
  output$text <- renderPrint({
    req(input$inSelect)
    country$code[match(input$inSelect,country$name)]
  })
}

shinyApp(ui, server)

enter image description here

data

country <- data.frame(name = c('Aruba', 'Afghanistan'), code = c('ABW', 'AFG'))
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • Thank you for the fast answer. I already thought about that, but it came into my mind, that it could be quite an expenditure, to search and match the value again. So I thought about a solution "inside" the selectizeInput. Also thanks again. I am only getting started with R, so I really had no Idea, how to implement that. – Moritz Jul 01 '21 at 15:00