I did quite a lot of research and did not find an answer to the following questions regarding the maps
package in R:
library(maps)
map_data('world')
This outputs the data from the data frame object. The columns are long, lat, group, order, region, and subregion. long and lat columns contain single values for longitude and latitude. No other geometry data is visible in the data frame.
map('world')
This plots a world map with country polygons.
So my questions are:
- Where is the geometry data of the polygons being stored?
- How can I access the geometry and work with it?
- How can I transform the geometry data to other useful formats like an
sf
object for example?
I am quite new to R and maybe the answers are quite simple. Anyways, I could not find them by myself and any help is highly appreciated.
EDIT: My goal is to visualise polygons from the 'world'
data of the maps
package on an interactive map using leaflet
. But if this is too complicated, I can use other sources for country polygons as well.
CodePudding user response:
You can convert the world
to sf
like:
map_obj <- maps::map("world", exact = FALSE, plot = FALSE, fill = TRUE)
map_obj |>
sf::st_as_sf()
#> Simple feature collection with 253 features and 1 field
#> Geometry type: MULTIPOLYGON
#> Dimension: XY
#> Bounding box: xmin: -180 ymin: -85.19218 xmax: 190.2708 ymax: 83.59961
#> Geodetic CRS: WGS 84
#> First 10 features:
#> ID geom
#> 1 Aruba MULTIPOLYGON (((-69.89912 1...
#> 2 Afghanistan MULTIPOLYGON (((74.89131 37...
#> 3 Angola MULTIPOLYGON (((23.9665 -10...
#> 4 Anguilla MULTIPOLYGON (((-63.00122 1...
#> 5 Albania MULTIPOLYGON (((20.06396 42...
#> 6 Finland MULTIPOLYGON (((20.61133 60...
#> 7 Andorra MULTIPOLYGON (((1.706055 42...
#> 8 United Arab Emirates MULTIPOLYGON (((53.92783 24...
#> 9 Argentina MULTIPOLYGON (((-64.54916 -...
#> 10 Armenia MULTIPOLYGON (((45.55235 40...
Created on 2022-10-20 with reprex v2.0.2
Regards, Grzegorz
CodePudding user response:
Here's my full working solution including leaflet
(simplified version of a project I'm currently working on). map()
instead of map_data()
as input for sf::st_as_sf()
did the trick, with some additional parameters proposed in Grzegorz Sapijaszko's answer.
library(maps)
library(leaflet)
map_obj <- map("world", exact = FALSE, plot = FALSE, fill = TRUE) |>
sf::st_as_sf()
leaflet() |>
addTiles() |>
addPolygons(data = map_obj)