简体   繁体   中英

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)

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
      )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM