闪亮:寻找简单的 selectInput 依赖解决方案

Shiny: in search of simple selectInput dependency solution

我正在尝试为用户选择的“州”dependent/reactive 的“县”创建一个简单的 selectInput 依赖函数。因此,用户在第一个下拉框中选择一个州,然后县下拉框应填充该州的县。然后为所选县创建案例数图表。到目前为止,我一直在兜圈子寻找最好的方法,但运气不佳。

以下当前形式的应用程序“正在运行”,但没有依赖性。因此,一旦选择了州,美国的所有县仍会列出。我知道问题出在县的 selectInput 语句上——我只是不确定哪个是让它依赖于州的最佳方式。我已经摸索了无数在线示例,但它们似乎不合适。非常感谢任何建议。

library(shiny)
library(dplyr)
library(ggplot2)

usdata <- read_csv("countyout.csv")

ui <- fluidPage(
   titlePanel("US Counties"),

  sidebarPanel(
    selectInput("state", "Select State:", choices = unique(as.character(usdata$state))),
    selectInput("county", "Select County:", choices = unique(as.character(usdata$county)))),
  
  mainPanel(
    plotOutput('casesplot', height = "300px")))

server <- function(input, output) {

  filtered <- reactive ({
     usdata %>%
      filter(state == input$state) %>%
      filter(county == input$county)
  })
  output$casesplot <- renderPlot({
      ggplot(data = filtered(), aes(x=date, y=cases)) + 
      geom_bar(stat = "identity")
  })
  }
shinyApp(ui = ui, server = server)

感谢 Ben 为我指明了正确的方向(请参阅他的评论中的 link)。我基本上需要将 ui 中的第二个 selectInput 语句更改为:

selectInput("countyin", "Select County", choices = NULL)

然后在服务器中添加观察语句以使选择反应:

observe({
    updateSelectInput(session, "countyin", "Select County", 
         choices = usdata[usdata$state == input$statein,]$county)
})