根据另一个 selectInput 的选择过滤一个 selectInput?

Filter one selectInput based on selection from another selectInput?

我有两个 selectInput,我希望第一个(品牌)中的选择更改第二个(糖果)中的可能选择。因此,例如,如果有人在第一个输入框中选择了 "Nestle",那么第二个输入框中将只显示雀巢糖果。我的数据 table 有一个品牌列和一个糖果棒类型列。

我有以下代码可以开始,但这显示了所有选择,无论选择如何。

selectInput(inputId="brand", 
                  label="Brand:",
                  choices=as.character
                  (unique(candyData$Brand)),
                  selected = "Nestle"
    ),
    selectInput(inputId="candy", 
                label="Candy:",
                choices=as.character
                (unique(candyData$Candy)),
                selected = "100Grand"

数据集如下所示:

Brand       Candy
Nestle      100Grand
Netle       Butterfinger
Nestle      Crunch
Hershey's   KitKat
Hershey's   Reeses
Hershey's   Mounds
Mars        Snickers
Mars        Twix
Mars        M&Ms

更新问题 如何根据后续筛选更新仪表板中的 ValueBox?

output$count <- renderValueBox({

    valueBox(
      value = nrow(candyData),
      subtitle = "Number of Candy Bars",
      icon = icon("table")
    )
  })

这是一种方法:

library(shiny)
library(shinydashboard)
##
ui <- shinyUI({
  sidebarPanel(

    htmlOutput("brand_selector"),
    htmlOutput("candy_selector"))

})
##
server <- shinyServer(function(input, output) {
  candyData <- read.table(
    text = "Brand       Candy
    Nestle      100Grand
    Netle       Butterfinger
    Nestle      Crunch
    Hershey's   KitKat
    Hershey's   Reeses
    Hershey's   Mounds
    Mars        Snickers
    Mars        Twix
    Mars        M&Ms",
    header = TRUE,
    stringsAsFactors = FALSE)

  output$brand_selector <- renderUI({

    selectInput(
      inputId = "brand", 
      label = "Brand:",
      choices = as.character(unique(candyData$Brand)),
      selected = "Nestle")

  })

  output$candy_selector <- renderUI({

    available <- candyData[candyData$Brand == input$brand, "Candy"]

    selectInput(
      inputId = "candy", 
      label = "Candy:",
      choices = unique(available),
      selected = unique(available)[1])

  })

})
##
shinyApp(ui = ui, server = server)

更新:

您可以将 ui 定义修改为

ui <- shinyUI({
  sidebarPanel(

    htmlOutput("brand_selector"),
    htmlOutput("candy_selector"),
    valueBoxOutput("count"))

})

并将以下内容添加到 server

output$count <- renderValueBox({

  available <- candyData[candyData$Brand == input$brand, ]

  valueBox(
    value = nrow(available),
    subtitle = sprintf("Number of %s Candy Bars", input$brand),
    icon = icon("table"))

})