'In R Shiny, use stats::setNames to assign names to vector elements and then retrieve the name attributes in the server side

I have a shiny app that displays data from a database, in which variables are assigned codes (e.g., "TMAX" for maximum temperature, "GDD" for growing degree days, etc). The user will pick a variable that they want to display from a selectInput, and I assigned names to the elements of the choices vector using stats::setNames(). In the full version of the app, figures are created displaying data for the selected variable, and I want to be able to use the name of the element as the y-label for the plot (for example, if the variable is TMAX, then I want the y axis to display "Max Temperature"). The names that I've assigned appear in the selectInput dropdown, but the name attribute appears to be lost when the user actually selects an option; when I call names() on the selected input, it returns NULL.

This mini app shows the issue. (I'm just printing and rendering the name of the variable rather than creating a figure with the name as the label.)

library(shiny)

ui <- fluidPage(
  selectInput(
    'select', 'Select',
    choices = stats::setNames(
      object = c('var1', 'var2', 'var3'),
      nm = c('Variable 1', 'Variable 2', 'Variable 3')
    )
  ),
  
  textOutput('var'),
  textOutput('varname')
) 

server <- function(input, output, session) {
  observeEvent(input$select, {
    print(names(input$select))
    
    output$var <- renderText(paste('Variable:', input$select))
    output$varname <- renderText(paste('Variable name:', names(input$select)))
  })
  
}

shinyApp(ui, server)

Thanks!



Solution 1:[1]

Thanks to @SmokeyShakers, I made the following changes (between the hashes):

library(shiny)
########
vars <- stats::setNames(
  object = c('var1', 'var2', 'var3'),
  nm = c('Variable 1', 'Variable 2', 'Variable 3')
)
########

ui <- fluidPage(
  selectInput(
    'select', 'Select',
    choices = vars
  ),
  
  textOutput('var'),
  textOutput('varname')
) 

server <- function(input, output, session) {
  observeEvent(input$select, {
    # print(names(input$select))
    
    output$var <- renderText(paste('Variable:', input$select))
    output$varname <- renderText(paste('Variable name:', 
                                       ########
                                       names(vars)[which(vars == input$select)]
                                       ########
                                      ))
  })
  
}

shinyApp(ui, server)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Slim