0
votes

I have a couple of columns with categorical data. I would like to create layers from these categorical data and plot them against a base map in R with leaflet. Each of these columns has 4 or more categories.

I am completely lost on how to attack this problem. I tried to do one category from one column and I got all points on the map back and the layer controlled all points which was not the expected behavior.

Here is what I have:

lihn_map <- leaflet(origAddress) %>%
  setView(lng = sv_lng, lat = sv_lat, zoom = sv_zoom) %>%
  addTiles(group = "OSM (default)") %>%
  addCircleMarkers(data = origAddress
    , radius = 3
    , fillOpacity = 1
    , group = "MI"
  ) %>%
  addProviderTiles(providers$Stamen.Toner, group = "Toner") %>%
  addProviderTiles(providers$Stamen.TonerLite, group = "Toner Lite") %>%
  # Overlay groups
  addCircles(~lat, ~lon, group = "MI") %>%
  addLayersControl(
    baseGroups = c("OSM (default)", "Toner", "Toner Lite"),
    overlayGroups = "MI",
    options = layersControlOptions(collapsed = FALSE)
  )

lihn_map

I am trying this loop, it adds the groups to the layer control but the selection does not change the map:

lsl <- unique(origAddress$LIHN_Line)

mt <- leaflet() %>%
  addTiles(group = "OSM (default)") %>%
  addProviderTiles(providers$Stamen.Toner, group = "Toner") %>%
  addProviderTiles(providers$Stamen.TonerLite, group = "Toner Lite")

for(i in 1:length(lsl)){
  l <- lsl[i]
  mt <- mt %>%
    addCircleMarkers(
      # I have also tried
      data = subset(origAddress, LIHN_Line = lsl[i])
      data = origAddress
      , group = lsl[i]
      , radius = 3
      , fillOpacity = 0.6)
}
mt <- mt %>%
  addLayersControl(
    baseGroups = c("OSM (default)", "Toner", "Toner Lite"),
    overlayGroups = lsl,
    options = layersControlOptions(collapsed = FALSE
      , position = "bottomright")
  )

mt My expectation is that this layer would only control the subset of data where the group is equal to MI Maybe I have to create subset data.frames? This seems inefficient if so and I'm sure is not the answer.

1

1 Answers

0
votes

I performed the following and it worked:

# for loop to cycle through adding layers
for(i in 1:length(lsl)){
  l <- lsl[i]
  mt <- mt %>%
    addCircles(
      data = subset(origAddress, origAddress$LIHN_Line == lsl[i])
      #data = origAddress
      , group = lsl[i]
      , radius = 3
      , fillOpacity = 0.6)
}

using subset worked brilliantly