Alex
Alex

Reputation: 15708

How to use selectInput to return value of a key corresponding to a label

In the package Shiny, the syntax:

  selectInput(inputId = "event_choice",
               label = "Choose event",
              selected = NULL,
               choices = events
  )

Displays a box telling users to choose an event from a drop down box populated with entries from the vector events. The user choice is then referenced by input$event_choice on the server side.

Consider the following data frame df:

event_id    events
________    _________
139         Alex visited on 2016-01-01
140         Alex left on 2016-02-01
150         ...

with the vector events = df$events.

Using this descriptive vector obviously makes it easier for the user to navigate the drop down in selectInput. However, when doing further subsets or operations on data, it is more useful and concise to use the event_id.

What is the best way to map the selected input to the event_id? I know I can use standard matching algorithms in the data.frame, but was wondering whether there was anything better in the context of Shiny.

Upvotes: 1

Views: 1273

Answers (1)

Xiongbing Jin
Xiongbing Jin

Reputation: 12097

Note the choice argument

choices List of values to select from. If elements of the list are named then that name rather than the value is displayed to the user.

So you can use a named list with names being events column and values being event_id column. As suggested by @alistaire in the comments below, an easy and straightforward way is

choices = setNames(df$event_id, df$event) 

Upvotes: 7

Related Questions