How I do a general function to insert the colors of the clusters? I used the leaflet package to generate the map. The way I did it was "if else", it worked, but if for example, I have 15 clusters, I will have many "if else". Can anybody help me ?? In addition, if possible I would like to put legend of the clusters on my map as well. My executable code is below:
library(leaflet)
library(geosphere)
#database
df<-structure(list(Properties = c(1,2,3,4,5,6,7,8,9,10), Latitude = c(-23.2, -23.6, -23.9, -23.9, -23.6, -23.5, -23.9, -23.9, -23.6, -23.9),
Longitude = c(-49.6, -49.6, -49.6, -49.4, -49.3, -49.9, -49.3, -49.2, -49.6, -49.9)), class="data.frame",row.names = c(NA, -10L))
#clusters
d<-as.dist(distm(df[,2:1]))
fit.average<-hclust(d,method="average")
clusters<-cutree(fit.average, 4)
df$cluster<-clusters
#Map using leaflet
example=df
getColor <- function(example) {
sapply(example$cluster, function(cluster) {
if(cluster == 1) {
"blue"
} else if(cluster == 2) {
"green"
} else if(cluster == 3) {
"orange"
} else {
"red"
} })
}
icons <- awesomeIcons(
icon = 'ios-close',
iconColor = 'black',
library = 'ion',
markerColor = getColor(example)
)
m=leaflet(example) %>% addTiles() %>%
addAwesomeMarkers(lat=~Latitude, lng = ~Longitude, icon=icons, label=~as.character(cluster))
m
Thank you very much!!
Insert addLegend
df1<-structure(list(Properties = c(1,2,3,4,5), Latitude = c(-23.8, -23.4, -23.2, -23.7,-23.8),
Longitude = c(-49.9, -49.2, -49.3, -49.1,-49.9)), class="data.frame",row.names = c(NA, -5L))
m = leaflet(example) %>% addTiles() %>%
addAwesomeMarkers(lat = ~ Latitude,lng = ~ Longitude,icon = icons,label = ~ as.character(cluster)) %>%
addLegend( position = "topright", title="Cluster", colors = ai_colors[1:max(df$cluster)],labels = unique(df$cluster))%>%
addAwesomeMarkers(leaflet(df1) %>% addTiles(), lat=~df1$Latitude, lng = ~df1$Longitude)
m
Image as example: