9

我有两个selectInputs,我希望第一个(品牌)中的选择可以更改第二个(糖果)中的可能选择。因此,例如,如果有人在第一个输入框中选择了“雀巢”,那么只有雀巢糖果棒会出现在第二个框中。我的数据表有一个品牌列和一个糖果棒类型列。

我有以下代码要启动,但这显示了所有选择,无论选择如何。

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

1 回答 1

12

这是一种方法:

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

})
于 2015-10-12T18:19:51.727 回答