Changing datasets based on select input in R shiny

Hi, I'm relatively new to shiny and having a bit of trouble switching between datasets. Basically, I want the user to select a crop. Each crop has it's own dataset, formatted in the same way (column names are the same), which then influences the rest of the select input options in the app.

This is my current attempt:

ui <- fluidPage(
            selectInput("cropId", "Crop Type",
                        c("Corn [bu/ac]" = "corn",
                          "Potato [cwt/ac]" = "pota")),
            # Select the county  
            selectInput("County", label = "County", choices = c("",as.character(CropData$County)),
                        selected = NULL, multiple = FALSE),
server <- function(input, output, session) {
    observeEvent(input$cropId,{
    datasetInput <- reactive({
        switch(input$cropId,
               "corn" = NASS_Corn_data,
               "pota" = NASS_Potato_data)
        CropData <- datasetInput()
        })
    })```

Hey there,
it might be useful if you could provide an exemple dataset with the first 5 rows or so and a reprex (minimal exemple to reproduce the problem) exemple of your App code. The above seems to be missing some parenthesese.
Plus, I am not sure as to what you are trying to achieve exactly as your code does not detail any output elements.
Do you want to display the data to the user as a table or plot?
Do you want to use the input dataset to compute calculations?

However, based on what you wrote I tried to approximate a solution. Does this help?

library(shiny)
ui <- fluidPage(
  selectInput("cropId", "Crop Type",
              c("Corn [bu/ac]" = "corn",
                "Potato [cwt/ac]" = "pota")),
  # Select the county  
  selectInput("County", label = "County", choices = c("County 1", "County 2", "County 3"),
              selected = NULL, multiple = FALSE),
  tableOutput("Crop_data")
)

server <- function(input, output, session) {
  
    NASS_Corn_data <- data.frame(Var1 = rnorm(5), 
                                 Var2 = c("This", "is", "corn", "information", "!"))
    NASS_Potato_data <- data.frame(Var1 = rnorm(5), 
                                 Var2 = c("This", "is", "potato", "information", "!"))
  
  
    # This returns the correct dataset
    datasetInput <- reactive({
      if (input$cropId == "corn"){
        dataset <- NASS_Corn_data
      }
      else if (input$cropId == "pota"){
        dataset <- NASS_Potato_data
      }
      return(dataset)
    })
    
    #This shows you the correct dataset
    output$Crop_data <- renderTable ({
      datasetInput()
    })
    
    

}

shinyApp(ui = ui, server = server)

This topic was automatically closed 54 days after the last reply. New replies are no longer allowed.