Shiny App Leaflet map doesn't filter correctly by year

Hello everyone !

I am new to Shiny and I am encountering some issues while trying to draw a map with leaflet in Shiny.

My goal is to crate a world map that displays death rates from obestity per country according to the selected year. I have created a Slider input for the user to select the year, used Add Circles to create circles whose size are proportional to the death rate and I also created different levels for the death rates (low, moderate and high) to color the circles.

However, when I run the code Shiny displays a map where there are many circles (and color) per year and country. Each circle corresponds to different death rates which are not even in my data set !

It looks like the filter fucntion has trouble filtering the data by year...

Anyone has an idea what the problem could be ?

Thank your for your help :blush:

Here is my code :

#load libraries
library(shiny)
library(leaflet)
library(dplyr)
library(leaflet.extras)
library(ggplot2)

#import data set
setwd('C:/Users/Clémentine/Documents/EDHEC/M2/R programming/Rprogramming')
deathrate<-read.csv("main_data/DeathRateFromObesity.csv")


typeof(deathrate$Year)
typeof(deathrate$Deaths.10k)

#Delete 2017 to match other data sets
mydeathrate0<-subset(deathrate,Year!=2017 & Code!='OWID_WRL' & Code!='TKL' & Code!='') 
mydeathrate=mydeathrate0%>%na.omit()

#Turn the death rates into percentages  
rateperk<-mydeathrate$Deaths.10k 
rate<-rateperk/100

#Add this column to the data set
mydata<- mydeathrate %>% mutate("death rate %" = rate) 

#Add longitude and latitude to the data frame (for the map)
setwd('C:/Users/Clémentine/Documents/EDHEC/M2/R programming/Rprogramming')

countries=read.csv("data/world_country_and_usa_states_latitude_and_longitude_values.csv")
countries=countries[,c(1,2,3,4)]

FinalData<-mydata

#creates new columns with longitude and latitude
namevector = c("latitude", "longitude")
FinalData[ , namevector] = NA

#adding latitude to the data frame
n=length(FinalData$Entity)
N=length(countries$country)
for (i in 1:n){
  for (j in 1:N){
    if (FinalData$Entity[i]==countries$country[j]){
      FinalData$latitude[i]=countries$latitude[j]
      FinalData$longitude[i]=countries$longitude[j]
    }
  }
  
}

#Create a new column to categorize the death rates into three levels
summary(FinalData$`death rate %`)# 1st quartile is 0.47, mean is 0.84, 3rd quartile is 1.1
FinalData$levels <- ifelse (FinalData$`death rate %` <= 0.47, FinalData$levels <- "Low",
                           ifelse(FinalData$`death rate %` <= 1.1,
                                  FinalData$levels <- "Moderate",
                                  FinalData$levels <- "High"
                           ))

#Checking the type of the variables in the data frame
typeof(FinalData$Year)
FinalData$levels<-as.factor(FinalData$levels)
FinalData$Entity=as.factor(FinalData$Entity)
FinalData$Year=as.integer(FinalData$Year) 
typeof(FinalData$Year)

#Shiny App 
# Define UI for application that draws a map
ui <- fluidPage(
  
  # Application title
  titlePanel("Death rate from obesity over time"),
  
  # Sidebar with a slider input for number of years 
  sidebarLayout(
    sidebarPanel(
      sliderInput(inputId = "SelYear",
                  label = "Select a year",
                  min = FinalData$Year%>%min,
                  max = FinalData$Year%>%max,
                  value = 1990, step = 1, animate = T, animationOptions(
                    interval = 100,
                    loop = FALSE                           )
      ),
    ),
      
    # Display a map
    mainPanel(
      leafletOutput(outputId = "mymap"),
    )
)
)


# Define server logic required to draw a map
server <- function(input, output) {

  #Define the colour palette associated with the three levels defined previously
  pal <- colorFactor(
    palette = c('blue', 'green', 'yellow'),
    domain = FinalData$levels
  )
  
  #create the map
  output$mymap<-renderLeaflet({
    leaflet()%>%
      setView(lng = -26,lat = 30,zoom = 1.5) %>%
      addTiles()%>%
      addCircles(data = FinalData %>% filter(FinalData$Year==input$SelYear),
                 lng = ~longitude, lat = ~latitude, weight = 1,
                 radius = ~(FinalData$`death rate %`) * 100000, 
                 popup = ~Entity,
                 label = ~as.character(paste0(Entity, Year, sep = " : ", FinalData$`death rate %`)),
                 color = ~pal(FinalData$levels)
      )
  })
}
  
shinyApp(ui=ui,server=server)

Please consider if this is a shiny issue, or not.
If not, you can produce a script showing example filtering and displaying a leaflet in Rstudio (just without the shiny framework to interactively set params).

if this is really a shiny issue, then you should familiarise yourself with the shiny debugging and reprex guide
shiny debug and reprex

if its a more fundamental leaflet, or tidyverse issue, then the standard reprex guide should help you to demonstrate that to us and get effective help.

FAQ: How to do a minimal reproducible example ( reprex ) for beginners

Hello, thank you for your quick answer and for this information ! I will narrow down the issue.

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

If you have a query related to it or one of the replies, start a new topic and refer back with a link.