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

时间:2015-10-12 17:32:28

标签: r shiny shinydashboard

我有两个selectInput,我想在第一个(Brand)中选择更改第二个(Candy)中的可能选择。所以,例如,如果有人选择了#34;雀巢"在第一个输入框中,只有雀巢糖果条将显示在第二个框中。我的数据表有一个Brand列和一个Candy bar类型列。

我有以下代码可以启动,但无论选择如何,都会显示所有选项。

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")
    )
  })

1 个答案:

答案 0 :(得分:11)

这是一种方法:

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"))

})