0

I would like to filter my leaflet map per year using crosstalk with the filter_select function like this example. So when we select a year it should change the data of the leaflet map. Unfortunately nothing happens. Here is some reproducible code:

library(tidyverse)
library(gapminder)
library(leaflet)
library(countrycode)
library(sf)
library(rnaturalearth)
library(crosstalk)

df <- gapminder %>% #filter(year == 2007) %>% 
  mutate(iso_a3 = countrycode(country, "country.name", "iso3c"), 
         gdpPercap = round(gdpPercap, 0), 
         lifeExp = round(lifeExp, 0))

world <- ne_countries(type = "countries",  returnclass = 'sf') %>% 
  left_join(., df, by = "iso_a3") %>% 
  filter(!is.na(country)) %>% 
  select("country", "continent" = "continent.y", "year", "lifeExp", "pop", "gdpPercap", "geometry") %>% 
  as('Spatial')

world_NA <- ne_countries(type = "countries",  returnclass = 'sf')

sd <-  SharedData$new(world)
sd_df <- SharedData$new(world@data, group = sd$groupName())

pal <- colorFactor(c("#1f77b4", "#ff7f0e", "#2ca02c", "#d62728", "#9467bd"), domain = c("Africa", "Americas", "Asia", "Europe", "Oceania"), ordered = FALSE)

bscols(
  list(
    filter_select("filter_year", "Choose the year:", sd_df, ~year),
    filter_slider("lifeExp", "Life expectancy (years):", sd_df, ~lifeExp),
    filter_slider("gdpPercap", "Income per person ($):", sd_df, ~gdpPercap)
  ),
  leaflet(sd) %>% 
    addProviderTiles("CartoDB.Positron") %>% 
    addPolygons(data = world_NA, color = "#969696", weight = 1, fillColor = "#808080") %>% 
    addPolygons(color = "#969696", weight = 2, fillColor = ~pal(continent), fillOpacity = 0.8)
)

Output:

enter image description here

As you can see when we change the year and some variable with the filter nothing happens. I think it has something to do with the sharedData but I don't know exactly.

1
  • As mentioned here the example (which is pretty old) does not use the CRAN version of leaflet. And the underlying issue is that crosstalk does not work with addPoylgons, .... See. here and here. But you can use devtools::install_github("dmurdoch/leaflet@crosstalk4") (see here) to make your code work.
    – stefan
    Commented Mar 1 at 11:33

0

Browse other questions tagged or ask your own question.