Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a "map" object to a "SpatialPolygon" object

Tags:

r

maps

maptools

sp

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"
like image 220
Mike.Gahan Avatar asked Sep 26 '14 14:09

Mike.Gahan


1 Answers

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"))
like image 93
Mike.Gahan Avatar answered Oct 18 '22 21:10

Mike.Gahan