1

I'm trying to create a simple selectInput dependent function for "counties" that is dependent/reactive on the user-selected "state". So, the user selects a single state in the first dropdown box, then a county dropdown box should populate with the counties for that state. A graph of # of cases is then created for the selected county. I've been swimming in circles on the best way to do this with no luck so far.

The app in its current form below is "working" but there's no dependency. So once the state is selected, all of the counties in the US are still listed. I know the issue is the selectInput statement for county -- I'm just not sure which is the best way to make it dependent on the state. I've fumbled through what seems like countless online examples, but they don't seem to fit. Any advice is much appreciated.

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)
wythe4
  • 83
  • 4
  • There was a recent question where answers were provided with examples that seem related here: https://stackoverflow.com/questions/62293044/r-shiny-what-is-the-problem-with-my-observe-function-updateselectinput ... using `updateSelectInput` to update the list of counties when a state is selected...does this help? – Ben Jul 18 '20 at 22:58
  • Can't believe I didn't stumble on that thread. Same problem, and your suggestion there worked for me too. Thank you! P.S. is there a way for me to mark your comment as a solution? -- I'm new to stackoverflow. – wythe4 Jul 19 '20 at 02:42
  • Please feel free to post your own answer, and include your code that worked for you. That may be helpful for others tackling the same problem in the future. – Ben Jul 19 '20 at 14:45

1 Answers1

1

Thanks to Ben for pointing me in the right direction (see link in his comment). I basically needed to change the second selectInput statement in the ui to:

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

and then add an observe statement in the server to make the selections reactive:

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