简体   繁体   中英

R Shiny - how to display choice label in selectInput

I defined a selectInput as below. I want to access the label of each choice, and render it on the main panel.

If the user selects "Sugar sweetened bev.", I want to render on the main panel something like this:

"You chose Sugar sweetened bev.", but instead I get "You chose ssb".

The reason I setup my selectInput choices this way is because I want the left-hand side for the title of the graph, and the right-side is the variable name.

Any advice or alternative direction is much appreciated!

 library(shiny)
 ui <- fluidPage(
 sidebarLayout(
  sidebarPanel(
     selectInput("foodvars", "Select food:",
                 choices = c("Beef/Pork" = "beefpork",
                             "Sugar sweeteened bev." = "ssb",
                             "Total fruit" = "total_fruit"))),
  mainPanel(
     textOutput("dispText")))
)
ui <- fluidPage(
 sidebarLayout(
  sidebarPanel(
     selectInput("foodvars", "Select food:",
                 choices = c("Beef/Pork" = "beefpork",
                             "Sugar sweeteened bev." = "ssb",
                             "Total fruit" = "total_fruit"))),
  mainPanel(
     textOutput("dispText")))
)
server <- function(input, output) {

output$dispText <- renderText({
 paste("You chose ",input$foodvars)})
}

shinyApp(ui = ui, server = server)

We create same named vector globally and then retrieve the name with names on a logical vector

library(shiny)
ui <- fluidPage(
  sidebarLayout(
    sidebarPanel(
      selectInput("foodvars", "Select food:",
                  choices = c("Beef/Pork" = "beefpork",
                              "Sugar sweeteened bev." = "ssb",
                              "Total fruit" = "total_fruit"))),
    mainPanel(
      textOutput("dispText")))
)

choiceVec <- c("Beef/Pork" = "beefpork",
               "Sugar sweeteened bev." = "ssb",
               "Total fruit" = "total_fruit")

server <- function(input, output) {

  output$dispText <- renderText({

    paste("You chose ",names(choiceVec)[choiceVec == input$foodvars])})
}

shinyApp(ui = ui, server = server)

-output

在此处输入图片说明

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