如何在Shiny中获得SelectInput的选择值?

如何获取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

最佳答案 从
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.

但是,这并不意味着app.R中定义的对象不能在UI和Server端使用,它们只属于不同的环境.

例如:

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)

《如何在Shiny中获得SelectInput的选择值?》

点赞