2

I'm working on a shiny app for a local school district that will display a flag for schools that shouldn't have recess based on air pollutant conditions. The app will filter for one specific day and I've added a column called recess that, based on air pollutants, is labelled either "Stay Inside!" or "Play On!". I've then created an icon list - a child playing icon for "Play on!" and a danger icon for "Stay Inside!".

Where I'm having trouble is with the function. I'm trying to get it to tell leaflet to display the child playing icon for the schools that can have recess that day and a danger icon for the schools that shouldn't have recess that day.

Here's an example of the problem I'm encountering:

# Load Libraries
library(tidyverse)
library(leaflet)



# Vectors
Schools <- c("CHS", "BHS", "DHS")
latitude <- c(60, 61, 62)
longitude <- c(100, 101, 102)
recess <- c("Stay Inside!", "Play on!", "Play on!")

# Data frame
bad_air <- data.frame(Schools, latitude, longitude, recess)

# Map Icons
recessIcons <- awesomeIconList(
  child = makeAwesomeIcon(icon = "child", library = "fa", 
                          markerColor = "blue"),
  danger = makeAwesomeIcon(icon = "exclamation", library = "fa", 
                           markerColor = "darkred")
)

# Function to grab map icon
getrecessIcon <- function(bad_air){
  sapply(bad_air$recess, function(recess){
    if(bad_air$recess == "Stay Inside"){
      recessIcons$child
    } else {
      recessIcons$danger
    }
  })
}

# Build Leaflet Map
leaflet(bad_air) %>%
  addProviderTiles(providers$CartoDB.Positron) %>% 
  addAwesomeMarkers(~longitude,
                    ~latitude,
                    icon = ~getrecessIcon(bad_air),
                    label = ~Schools,
                    labelOptions = labelOptions(noHide = F))

Then I get this error:

Warning messages:
1: In if (bad_air$recess == "Stay Inside") { :
  the condition has length > 1 and only the first element will be used
2: In if (bad_air$recess == "Stay Inside") { :
  the condition has length > 1 and only the first element will be used
3: In if (bad_air$recess == "Stay Inside") { :
  the condition has length > 1 and only the first element will be used

Where am I going wrong? Any help would be GREATLY appreciated!

Keith
  • 23
  • 2

1 Answers1

1

I think this could be simplified without using the function.

Add a column icon to indicate which icon you want to use for each school/row:

bad_air$icon <- ifelse(bad_air$recess == "Stay Inside!", "danger", "child")

Then, access the icon you need for each school by selecting the appropriate icon from recessIcons that you created (i.e., recessIcons[icon]):

# Build Leaflet Map
leaflet(bad_air) %>%
  addProviderTiles(providers$CartoDB.Positron) %>% 
  addAwesomeMarkers(~longitude,
                    ~latitude,
                    icon = ~recessIcons[icon],
                    label = ~Schools,
                    labelOptions = labelOptions(noHide = F))
Ben
  • 20,394
  • 4
  • 17
  • 35