Reputation: 87
I have a shiny app that I am building with interactive maps in it. I am primarily using leaflet
to do this.
I added new data (statistics and whatnot) to a SpatialPolygonsDataframe in the map@data
section of the df
(map
being the SpatialPolygonDataframe).
map <- readOGR("FilePath","map")
#merge the processed dataframe with the maps data
map@data = merge(map@data, stats, by= 'name',
all = TRUE)
name | OBJECTID | ID_NUM | SHAPE_Leng | SHAPE_Area | Stat1 | Stat2 |
---|---|---|---|---|---|---|
First | 1 | 3 | x1 | y1 | .90 | 32 |
Second | 2 | 4 | x2 | y2 | .85 | 33 |
the R package Leaflet
will not apply the correct data to the correct area on the map unless I write:
map@data <- map@data[order(map@data$OBJECTID),]
It needs to be sorted in descending order on this column OBJECTID
to show the labels correctly.
Why does sorting map
differently, mostly for labeling purposes, cause leaflet to label the shapes incorrectly? (This question is for understanding this type of data and package better).
All of the examples I have seen don't have this is issue. And they either hide or dont have code that sort the data by descending or ascending in the legend.
This sorting affects the legend too.
How can I sort the legend (which shows the data I added to df
) how I need it to? (be it through leaflet or map
through dplyr)
Upvotes: 0
Views: 30
Reputation: 8749
It seems you are using the older {sp} package workflow. It does not have so strict pairing between data (in the @data slot) and geometry as the newer {sf} package. {sp} is older, and rather risky (for exactly this reason) - and while it is maintained (mainly to give time to users of existing workflows to migrate) it is not actively developed - the action happens in {sf}. If you have your packages at current version you should be seeing a big fat deprecation warning when you load {rgdal} (where rgdal::readOGR()
lives).
I suggest you update your workflow to {sf}, which has much tighter pairing between geometry (in a special list column) and regular tabular data (other columns).
Upvotes: 0