I am displaying a selectInput in my shiny app and it is getting its choices from a dataframe (which is coming from a table in the database).
this table (dataframe) has primary key and title in it. I want to show my users the title, but when they choose an option, I want to get the Id of the selected option to use in my code.
I managed to get the selected "value" but I couldn't find how to get the "id" from the selected option.
below is a simple example of how my code is looking with test objects:


library(DT)
library(tidyverse)
library(shiny)




test_id <- c(1, 2, 3)
test_title <- c("a", "b", "c")

test_df <- data.frame(test_id, test_title)
test_df <- column_to_rownames(test_df, var = "test_id")


ui <- fluidPage(
  selectInput("test", "test", choices = test_df),
  
  textOutput("selectedItem")
  
)

server <- function(input, output, session) {
  
  observeEvent(input$test, {
    output$selectedItem <- renderText(input$test)
  })
  
  
    
}

shinyApp(ui, server)


does anyone have a solution to get the "id" of the selected option?
I have tried this
output$selectedItem <- renderText(input$test)

but it is returning the value and not the Id

How can I get the primary key of a selected option from a dataframe-based selectInput in Shiny?
You could pass a named vector or list to the choices argument.
From the docs (?selectInput):

If elements of the list are named, then that name — rather than the value — is displayed to the user.

library(tidyverse)
library(shiny)

test_id <- c(1, 2, 3)
test_title <- c("a", "b", "c")

test_df <- data.frame(test_id, test_title)
choices <- setNames(test_df$test_id, test_df$test_title)

ui <- fluidPage(
  selectInput("test", "test", choices = choices),
  textOutput("selectedItem")
)

server <- function(input, output, session) {
  observeEvent(input$test, {
    output$selectedItem <- renderText(input$test)
  })
}

shinyApp(ui, server)
#> 
#> Listening on http://127.0.0.1:5936


