Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
406 views
in Technique[技术] by (71.8m points)

r - Converting a "map" object to a "SpatialPolygon" object

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"
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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"))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...