Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get choices values of SelectInput in Shiny?

Tags:

shiny

How can I get the list of choices in a SelectInpute?

ui.R

selectInput(inputId = "select_gender", 
    label = "Gender",
    choices = c("Male","Female"),
    width = 150
)

server.R

# Something like...

genders <- input$select_gender["choices"]

# So that the gender would be:

> genders

[1] Male Female
like image 491
BeBa Avatar asked Jun 29 '16 04:06

BeBa


1 Answers

From the scoping rules of Shiny:

Objects defined in global.R are similar to those defined in app.R outside of the server function definition, with one important difference: they are also visible to the code in the ui object. This is because they are loaded into the global environment of the R session; all R code in a Shiny app is run in the global environment or a child of it.

However, this doesn't mean that objects defined in the app.R can't be used on both the UI and Server side, they just belong to a different environment.

For example:

library("shiny")
library("pryr")

# or in global.R
genders <- c("Male", "Female")
gen_env <- where("genders")
par_env <- parent.env(gen_env)

ui <- fluidPage(
  selectInput("shiny_gender", "Select Gender", choices = genders),
  verbatimTextOutput("selected_gender_index"),
  p("The `genders` object belongs to the environment:"),
  verbatimTextOutput("gen_env_print"),
  p("Which is the child of the environment:"),
  verbatimTextOutput("par_env_print")
)

server <- function(input, output) {
   output$selected_gender_index <- renderPrint({
     # use the 'genders' vector on the server side as well
     which(genders %in% input$shiny_gender)
   })

   output$gen_env_print <- renderPrint(gen_env)
   output$par_env_print <- renderPrint(par_env)
}

shinyApp(ui = ui, server = server)

enter image description here

like image 135
mlegge Avatar answered Jan 02 '23 10:01

mlegge