Home > Software design >  R R-Leaflet addAwesomeMarkers. How to set conditional colours based on column values (character)
R R-Leaflet addAwesomeMarkers. How to set conditional colours based on column values (character)

Time:07-08

Using leaflet and addAwesomeMarkers, I want to vary the color of the map marker according to the value of a specific column.

Using the quakes data, i can vary color according to a mutated column if the contents of that column is numeric:

data(quakes)
quakes<-
quakes %>% mutate(
  type = ifelse(stations > 60, 1,2)
)

getColor <- function(quakes) {
  sapply(quakes$type, function(type) {
  if(type == 1) {
    "green"
  } else {
    "red"
  } })
}

icons <- awesomeIcons(
  icon = 'ios-close',
  iconColor = 'black',
  library = 'ion',
  markerColor = getColor(quakes[1:20, ])
)

leaflet(quakes[1:20, ]) %>% addTiles() %>%
  addAwesomeMarkers(~long, ~lat, icon=icons, label=~as.character(mag))

Resulting in:

However, if the mutated column contains character data, the color variation of the 'else' statement is assigned to all pins:

quakes<-
quakes %>% mutate(
  type = ifelse(stations > 60, "foo","bar")
)

getColor <- function(quakes) {
  sapply(quakes$type, function(type) {
  if(type == "foo") {
    "green"
  } else {
    "red"
  } })
}

icons <- awesomeIcons(
  icon = 'ios-close',
  iconColor = 'black',
  library = 'ion',
  markerColor = getColor(quakes[1:20, ])
)

enter image description here

The console also displays the following Input to asJSON(keep_vec_names=TRUE) is a named vector. In a future version of jsonlite, this option will not be supported, and named vectors will be translated into arrays instead of objects. If you want JSON object output, please use a named list instead. See ?toJSON.

Am I missing something here? How can I set the condition for the color allocation to check character values from the data?

Many thanks

CodePudding user response:

Could you use the ifelse() function in the awesomeIcons() function?

library(leaflet)
data(quakes)

quakes<-
  quakes %>% mutate(
    type = ifelse(stations > 60, "foo","bar")
  )

icon <- awesomeIcons(
  icon = 'ios-close',
  iconColor = 'black',
  library = 'ion',
  markerColor = ifelse(quakes$type == 'foo', 'green', 'red'))

leaflet(quakes[1:20, ]) %>% addTiles() %>%
  addAwesomeMarkers(~long, 
                    ~lat, 
                    icon= icon, 
                    label=~as.character(mag))
  • Related