0

I have a code below, and I would like to forloop the overlayGroup by each cluster.

enter image description here

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()
2
  • 1
    data %>% filter(cluster == i) seems wrong? i is an integer between 1 and k (number of clusters (3)). This filter will not match your clusters, which are named 1st.C etc.
    – VvdL
    Commented Jun 3, 2022 at 13:48
  • instead of for (i in 1:k) { use for (i in cluster) {
    – einar
    Commented Jun 3, 2022 at 16:04

1 Answer 1

1

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])

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