So I found a quite similar question, here on SO, but I am unable to get it fixed for my problem. I am building a map in Shiny leaflet. What I want, is when a certain variable has certain values (conditions), make a addAwesomeMarkers()
; else, make a addCircleMarkers()
. I've tried some if (else)
, case_when()
and mutate()
statement, but am unable to fix it. So... here's my code.
Packages:
library(dplyr)
library(ggplot2)
library(leaflet)
library(reshape2)
library(shiny)
library(tidyr)
Dummy dataset:
NAME VAR WAIT latitude longitude
a 4 1 52,6263 4,7312
b 3 52,2946 4,9585
c 6 8 52,3331 6,6468
d 8 5 51,2864 4,0492
e 7 6 50,9832 5,8446
Code:
leafletOutput('myMap', width = '80%', height = 600)
output$myMap <- renderLeaflet({
getColor <- function(DATASET) {
sapply(DATASET$WAIT, function(WAIT) {
if(WAIT == 0 | is.na(WAIT) | is.nan(WAIT)) {"gray"}
else if(WAIT <= 1){"darkgreen"}
else if(WAIT <= 2){"green"}
else if(WAIT <= 4){"lightgreen"}
else if(WAIT <= 6){"orange"}
else if(WAIT <= 8){"red"}
else {"darkred"}
})
}
icons <- awesomeIcons(
icon = 'heart-o',
lib = 'fa',
iconColor = "#FFFFFF",
markerColor = getColor(DATASET))
map <- leaflet(DATASET) %>%
addTiles() %>%
# DATASET$VAR is a char in my dataset
{if (DATASET$VAR == "4") filter(., addAwesomeMarkers(lng = ~longitude, lat = ~latitude, icon = icons,
label = ~as.character(DATASET$NAME),
popup = paste0("<strong>Name: </strong>", DATASET$NAME)))
else filter(., addCircleMarkers(lng = ~longitude, lat = ~latitude, radius = 10, label = ~as.character(DATASET$NAME),
popup = paste0("<strong>Name: </strong>", DATASET$NAME)))} %>%
addProviderTiles(providers$OpenStreetMap)
})
So my if else ain't working; giving the following error:
no applicable method for 'filter_' applied to an object of class "c('leaflet', 'htmlwidget')"
I tried implementing a mutate()
. Thanks in advance for any help!