I would like to change data to plot on a shapefile (world) based on the year selected as input. According to you, which one is wiser:
Setting the data to wide (data_2020, data_2019, data_2018...) and change the column when the input changes ? -or-
Setting the data to long (data, year) and filter the data column based on year == 20XX when the input changes ?
I've been trying for days but couldn't manage to make it work. The example below is my server.R
file where data has been set to long format and I selected one year in order to make reactivity work, but it doesn't update the data. The wide format does not work with the (commented) switch function.
function(input, output) {
selectedYear <- reactive({
#shape_data <- subset(shape_data, year == input$year)
shape_data$month
#datayear <- switch(input$year,
# "2017" = shape_data$month2017,
# "2018" = shape_data$month2018,
# "2019" = shape_data$month2019)
})
output$mymap <- renderLeaflet({
bins <- c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)
pal <- colorBin(c("#3EA055", "#FFE5B4", "#F2BB66", "#FFDB58", "#FBB117", "#C68E17", "#E56717", "#C34A2C", "#C11B17", "#9F000F", "#8C001A" , "#7E3517"), domain = selectedYear(), bins = bins, na.color = "#808080")
leaflet(shape_data) %>%
setView(0, 37.8, 2) %>%
addTiles() %>%
addPolygons(fillColor = ~pal(selectedYear()),
weight = 2,
opacity = 1,
color = "black",
fillOpacity = 0.7)
})
observe({
req(input$year)
bins <- c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)
pal <- colorBin(c("#3EA055", "#FFE5B4", "#F2BB66", "#FFDB58", "#FBB117", "#C68E17", "#E56717", "#C34A2C", "#C11B17", "#9F000F", "#8C001A" , "#7E3517"), domain = selectedYear(), bins = bins, na.color = "#808080")
leafletProxy("mymap", data = shape_data) %>%
clearShapes() %>%
addPolygons(fillColor = ~pal(selectedYear()),
weight = 2,
opacity = 1,
color = "black",
fillOpacity = 0.7)
})
Your statement
shape_data <- subset(shape_data, year == input$year)
changes shape_data
after the first year selection. Please change it to
shape_data2 <- subset(shape_data, year == input$year)