'Filter a data frame in accordance with the values ​assumed by the sidebar panels

I have the following panels:

# ui.R
# rest of the code
selectizeInput(
  "year",
  "Select a year",
  choices = c(2004, 2005, 2006, 2007),
  multiple = FALSE
),
selectizeInput(
  "indicators",
  "Select the indicators",
  choices = c("Economics", "Society", "Politics", "Culture", "Tourism"),
  multiple = TRUE
)
# rest of the code

Now, in server.R i want to filter a data frame in accordance with the previous choices. Is the following way correct?

observeEvent(c(input$anno, input$indicatori),
  {
    df %>% filter(YEAR == input$year & INDICATOR %in% as.vector(input$indicators))
    # rest of the code
  }
)


Solution 1:[1]

You should try to use a reactive dataframe, instead of observeEvent.

Updating the reactive automatically updates all plots and tables :

filtered_data <- reactive({
  df %>% 
    filter(YEAR == !!input$year & 
           INDICATOR %in% as.vector(!!input$indicators))

})
#output$myplot <- renderPlot(plot(filtered_data()))
#output$mytable <- renderTable(filtered_data())

Note the use of !! before using shiny inputs in dplyr

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 HubertL