显示selectInput with list的分组

时间:2018-03-08 19:03:36

标签: r shiny

在下面的代码中,selectInput的输出只是选择,但也不是分组变量。我想能够说出它来自哪个分组。示例You Chose Gender - Female。如何将分组变量拉出来?

if (interactive()) {

  # basic example


  # demoing optgroup support in the `choices` arg
  shinyApp(
    ui = fluidPage(
      selectInput("state", "Choose a state:",
                  list(`State` = c("NY", "NJ", "CT"),
                       `Gender` = c("Female","Male"),
                       `Region` = c("North", "West", "East"))
      ),
      textOutput("result")
    ),
    server = function(input, output) {
      output$result <- renderText({
        paste("You chose", input$state)
      })
    }
  )
}

1 个答案:

答案 0 :(得分:1)

您可以像这样实现:

library(purrr) # install.packages('purrr')
library(shiny)

choices <- list(
  `State` = c("NY", "NJ", "CT"),
  `Gender` = c("Female","Male"),
  `Region` = c("North", "West", "East")
)

shinyApp(
  ui = fluidPage(
    selectInput(
      "state",
      "Choose a state:",
      choices <- choices
    ),
    textOutput("result")
  ),
  server = function(input, output) {
    output$result <- renderText({
      paste(
        "You chose",
        input$state,
        "from",
        names(choices)[choices %>% map_lgl(~input$state %in% .)]
      )
    })
  }
)

但是在不同类别下有重复选项时可能存在问题。这可以通过使用名称和值(在整个列表中唯一)对作为列表元素来解决。见下文。

# 'Region' and 'Direction' both have an option 'North' but can be distinguished by the value. Note you should use values in your app logic.

library(purrr) # install.packages('purrr')
library(shiny)
choices <- list(
  State = c("NY", "NJ", "CT"),
  Gender = c("Female", "Male"),
  Region = c("North" = "reg_north", "West" = "reg_west", "East" = "reg_east"),
  Direction = c("North" = "dir_north", "South" = "dir_south")
)

shinyApp(
  ui = fluidPage(
    selectInput(
      "state", "Choose a state:",
      choices <- choices
    ),
    textOutput("result")
  ),
  server = function(input, output) {
    output$result <- renderText({
      paste(
        "You chose",
        input$state,
        "from",
        names(choices)[choices %>% map_lgl(~input$state %in% .)]
      )
    })
  }
)