Search code examples
rshinyshinywidgets

pickerInput names and values from dataframe R Shiny


I'm not sure if I'm just not searching the right thing, but I'm not able to find an answer.

I have a Shiny dashboard which has a picker to subset dataframe columns.

I have another dataframe which contains two columns:

  • The column name to appear in the picker choices
  • The corresponding column name as it appears in the dataframe.
dat <- data.frame(
  names = c("CODE", "STATE_OR_PROVINCE", "LOCATION_CODE"),
  display = c("Code", "State or province", "Location code")
)

What I want is to simply have dat$display = dat$names in the choices = list() argument inside of pickerInput, but that throws an error.

How can I achieve this? I know I can do it manually using:

          pickerInput(
            "example",
            "Example: ",
            choices = c(list("Code" = "CODE"),
                        list("State or province" = "STATE_OR_PROVINCE"),
                        list("Location code" = "LOCATION_CODE")
                        )
          )

But this rapidly becomes cumbersome the more choices there are.

Reproducible example:

library(shiny)
library(tidyverse)
library(shinyWidgets)

dat <- data.frame(
  names = c("CODE", "STATE_OR_PROVINCE", "LOCATION_CODE"),
  display = c("Code", "State or province", "Location code")
)
ui <- fluidPage(


    sidebarLayout(
        sidebarPanel(
          pickerInput(
            "example",
            "Example: ",
            choices = c(list("Code" = "CODE"),
                        list("State or province" = "STATE_OR_PROVINCE"),
                        list("Location code" = "LOCATION_CODE")
                        )
          )
        ),
        mainPanel()
    )
)


server <- function(input, output) {
  observe({
    input$example %>% glimpse()
  })
   
}

# Run the application 
shinyApp(ui = ui, server = server)

Solution

  • You can use a named vector for the choices argument:

    choices_data <- dat$names
    names(choices_data) <- dat$display
    
    pickerInput(
            "example",
            "Example: ",
            choices = choices_data
          )