Leaflet chorolpleth with reactive layer

I am trying to build a leaflet choropleth map from a reactive layer. I can make a plain one (same colours on the fill) , but can't get the choropleth to work. Any ideas on how to make it work?

Warning: Error in pal: unused argument (AREA)

library(shiny)
library(sf)
library(tidyverse)
library(leaflet)

# data in the sf package
nc <- st_read(system.file("shape/nc.shp", package="sf")) %>% 
    select(NAME, AREA, SID74)

nc_names <- nc %>% 
    st_set_geometry(NULL) %>% 
    distinct(SID74) %>%
    arrange(SID74) %>% 
    pull()

# Define UI for application that draws a histogram
ui <- fluidPage(    
    # Generate a row with a sidebar
    sidebarLayout(      
        # Define the sidebar with one input
        sidebarPanel(
            selectInput("name",
                        "name",
                        nc_names
            )
        ),
        # Create a spot for the barplot
        mainPanel(
            mainPanel(leafletOutput("map") )
        )
    )
)

server <- function(input, output) {
    
    # filter polygon for map based on location selected
    shp_selected <- reactive({
        req(input$name)
        nc %>% filter(SID74 == input$name)       
    })
    
    # colours and bins
    bins <- c(0, 0.2, 0.4, Inf)
    pal <- reactive({
        colorBin("YlOrRd", domain = shp_selected()$AREA, bins = bins)
    })
    
    output$map <- renderLeaflet( {
        leaflet() %>% 
            addProviderTiles("Stamen.TonerHybrid") %>% 
            addPolygons(data = shp_selected(), 
                        fillColor =  ~pal(AREA), #"blue",
                        fillOpacity = 0.5,
                        weight = 1,
                        stroke = TRUE,
                        color = "black", 
                        opacity = 1,
                        layerId = ~NAME) 
    })
    
}

shinyApp(ui, server)

It works by moving where data is called.

shp_selected() %>%
    leaflet() %>%

Then removing data = shp_selected()

Actually, I have noticed that my example is not completely reproducible, but this is what works with my real dataset. I might have done something a little different there.

1 Like