Search code examples
rshinyr-leaflet

How to set marker color according to a column?


I need to make make circles different colors based on if condition. I added if statement to color= parameter but all circles are coloured only in one color, so it'doesn't work. I base on standard quakes dataset and need to differ colours based on depth>300 condition. I tried to use lapply but not sure if I do it correctly: lapply(if(coords$depth > 300) 'red' else 'green',htmltools::HTML). Anyways, do you have any idea how to make it possible?

library(shiny)
library(leaflet)
library(dplyr)
library(sf)
library(htmlwidgets)


ui <- fluidPage(
   leafletOutput("map")
)

server <- function(input, output, session) {
   
   coords <- quakes %>%
      sf::st_as_sf(coords = c("long","lat"), crs = 4326)

     output$map <- leaflet::renderLeaflet({
     leaflet::leaflet() %>%         
       leaflet::addTiles() %>%
       leaflet::setView(172.972965,-35.377261, zoom = 4) %>%
       leaflet::addCircleMarkers(
         data = coords,
         stroke = FALSE,
         color = if(coords$depth > 300) 'red' else 'green',
         radius = 6)
   })
}

shinyApp(ui, server)

Solution

  • library(tidyverse)
    library(leaflet)
    
    data(quakes)
    
    quakes[1:20, ] %>%
      leaflet() %>%
      addTiles() %>%
      addCircleMarkers(~long, ~lat,
        popup = ~ as.character(mag),
        label = ~ as.character(mag),
        color = ~ ifelse(depth > 300, "red", "green")
      )
    

    enter image description here