[GIS] Displaying sum of frequencies in leaflet cluster maps pointer

leafletleaflet-rr

I've a dataset with locations and their frequencies (sum of counts)

I want the leaflet cluster to display the frequencies as pointers instead of the count of occurrences.

city            state   latitude    longitude   Count

San Juan        PR      18.410462   -66.060533  5
Honolulu        HI      21.2782     -157.82199  8
Boca Raton      FL      26.391346   -80.21824   17
Key Biscayne    FL      25.700966   -80.16195   2

I use the function

leaflet(df) %>% addTiles() %>% addMarkers(
  clusterOptions = markerClusterOptions(),
)

to display the map, but it displays the count of each location pointer as one, regardless of the frequency. How do I customize the code so that it displays the frequencies instead of counts in pointers ?

This is how I want my end result as

http://leaflet.github.io/Leaflet.markercluster/example/marker-clustering-custom.html

Best Answer

One possible answer is expand your data.frame by the column Count. Doing this, you will have n number of points (based on Count) for every location.

Try the reproducible example below:

# Load libraries
library('leaflet')

# Load data
df <- data.frame('city' = c("San Juan", "Honolulu", "Boca Raton", "Key Biscayne"),
                 'state' = c("PR", "HI", "FL", "FL"),
                 'latitude' = c(18.410462, 21.2782, 26.391346, 25.700966),
                 'longitude' = c(-66.060533, -157.82199, -80.21824, -80.16195),
                 'Count' = c(5, 8, 17, 2))

# Expand dataframe
df.expanded <- df[rep(row.names(df), df$Count),]

# Leaflet map of df
leaflet(df.expanded) %>% addTiles() %>% 
  addMarkers(clusterOptions = markerClusterOptions())

clustermap

Notice that in the figure there are 19 points in yellow because "Boca Raton" (Count = 17) and "Key Biscayne" (Count = 2) are collapsed at that level of zoom.