Converting a “map” object to a “SpatialPolygon” object

夙愿已清 提交于 2019-11-27 03:15:06

问题


I am guessing there is a simple solution to the problem I have been having, but I am having some trouble.

I am trying to convert the following map object:

require(maps)
usa <- map("state")

into a SpatialPolygon object using the map2SpatialPolygons function:

require(maptools)
usa.sp <- map2SpatialPolygons(usa, IDs=usa$names,proj4string=CRS("+proj=longlat"))

I keep getting the following error:

Error in map2SpatialPolygons(usa, IDs = usa$names, proj4string = CRS("+proj=longlat")) : 
  map and IDs differ in length

After some research, it looks like the IDs have length 63 and the map object has length 169 after applying the function .NAmat2xyList(cbind(map$x, map$y)) (for which I cannot find the source to).

Anyone have any ideas? Here is the structure of the usa map object:

> str(usa)
List of 4
 $ x    : num [1:1705] -88.4 -88.1 -88 -87.9 -87.8 ...
 $ y    : num [1:1705] 30.4 30.4 30.8 30.6 30.3 ...
 $ range: num [1:4] -124.7 -67 25.1 49.4
 $ names: chr [1:63] "alabama" "arizona" "arkansas" "california" ...
 - attr(*, "class")= chr "map"

回答1:


Just found some code in the text "Applied Spatial Data Analysis with R". It works great!

require(maps)
usa <- map("state", fill = TRUE)

require(sp)
require(maptools)
IDs <- sapply(strsplit(usa$names, ":"), function(x) x[1])
usa <- map2SpatialPolygons(usa, IDs=IDs, proj4string=CRS("+proj=longlat +datum=WGS84"))



回答2:


Polygons have surface (area), therefore the key argument is fill = TRUE in

usa <- map('state', fill = TRUE)

Changing the argument value to TRUE stops the error message.



来源:https://stackoverflow.com/questions/26062280/converting-a-map-object-to-a-spatialpolygon-object

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!