I have a code below, and I would like to forloop
the overlayGroup
by each cluster.
library(dplyr); library(leaflet); library(raster);library(htmltools)
cluster <- c("1st.C", "2nd.C", "3rd.C")
lat <- c(40.8518, 42.6611, 37.3089)
long <- c(14.2681, 13.6987, 13.5858)
data <- data.frame(cluster, lat, long); data
adm <- raster::getData('GADM', country= "italy" , level=1)
map_layers <- function() {
#number of groups
k <- n_distinct(data$cluster)
#base map
map <- leaflet() %>%
addProviderTiles(providers$CartoDB.Positron)
#loop through all groups and add a layer one at a time
for (i in 1:k) {
map <- map %>%
addCircleMarkers(
data = data %>% filter(cluster == i), group = as.character(i),
radius = 3, lng = ~long, lat = ~lat
)
}
#create layer control
map %>%
addLayersControl(
overlayGroups = c(1:k),
options = layersControlOptions(collapsed = FALSE)) %>%
hideGroup(as.character(c(2:k))) #hide all groups except the 1st one
}
#plot the map
map_layers()
i think this is what you are trying to achieve:
leaflet() %>%
addProviderTiles(providers$CartoDB.Positron) %>%
addCircleMarkers(data = data,
radius = 3, lng = ~long, lat = ~lat, group = cluster) %>%
addLayersControl(overlayGroups = cluster,
options = layersControlOptions(collapsed = FALSE)) %>%
hideGroup(group = data$cluster[2:3])