Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R Shiny - how to display choice label in selectInput

Tags:

r

shiny

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)
like image 884
Faith Avatar asked Jan 05 '18 02:01

Faith


1 Answers

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

enter image description here

like image 139
akrun Avatar answered Oct 02 '22 14:10

akrun