1

Look at my R code, here I am able to mark two different types of marker icon but I want to mark for all the 10 values of quakes$mag column with 10 different types of marker icons.

 quakes1 <- quakes[1:10,]

leafIcons <- icons(
  iconUrl = ifelse(quakes1$mag < 4.6,
                   "http://leafletjs.com/examples/custom-icons/leaf-green.png",
                   "http://leafletjs.com/examples/custom-icons/leaf-red.png"
  ),
  iconWidth = 38, iconHeight = 95,
  iconAnchorX = 22, iconAnchorY = 94,
  shadowUrl = "http://leafletjs.com/examples/custom-icons/leaf-shadow.png",
  shadowWidth = 50, shadowHeight = 64,
  shadowAnchorX = 4, shadowAnchorY = 62
)

leaflet(data = quakes1) %>% addTiles() %>%
  addMarkers(~long, ~lat, icon = leafIcons)

I tried to do it with switch statement instead of ifelse, but it is not working with switch.

1 Answer 1

0

Your ifelse is a vectorized function that created your vector of icons for leafIcons. There are various ways you can vectorize switch or alternatives to create your leafIcons based on a vector - see this related question. With dplyr you can use case_when which might be what you are looking for:

library(dplyr)
library(leaflet)

leafIcons <- icons(
  iconUrl = case_when(
    quakes1$mag <= 4.3 ~ "http://leafletjs.com/examples/custom-icons/leaf-green.png",
    4.3 < quakes1$mag & quakes1$mag <= 5 ~ "http://leafletjs.com/examples/custom-icons/leaf-orange.png",
    quakes1$mag > 5 ~ "http://leafletjs.com/examples/custom-icons/leaf-red.png"
  ),
  iconWidth = 38, iconHeight = 95,
  iconAnchorX = 22, iconAnchorY = 94,
  shadowUrl = "http://leafletjs.com/examples/custom-icons/leaf-shadow.png",
  shadowWidth = 50, shadowHeight = 64,
  shadowAnchorX = 4, shadowAnchorY = 62
)

You can also use cut or findInterval if you have a numeric vector that you want to assign icons to different ranges.

Not the answer you're looking for? Browse other questions tagged or ask your own question.